<template>
  <div class="add-tender-container">
    <!-- 步骤条 -->
    <div class="steps-container">
      <el-steps :active="activeStep" finish-status="success">
        <el-step title="标书设置" />
        <el-step title="需求明细" />
        <el-step title="编写目录" />
        <el-step title="编写正文" />
      </el-steps>
    </div>
    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 标书设置 -->
      <div v-if="activeStep === 0">
        <!-- 标书标题 -->
        <div class="setting-item">
          <h3 class="setting-title">标书标题</h3>
          <el-input
            v-model="tenderTitle"
            placeholder="请输入标书标题"
            maxlength="50"
            show-word-limit
          />
        </div>
        <!-- 标书页数 -->
        <div class="setting-item">
          <h3 class="setting-title">标书字数</h3>
          <div class="page-count-slider">
            <el-slider
              v-model="wordCount"
              :min="0"
              :max="100000"
              :step="1"
              @input="updatePageCount"
            />
          </div>
          <div class="word-count-info">
            <el-alert
              title="预计页数"
              :description="`共${wordCount}字，约 ${pageCount} 页，每页800字`"
              type="info"
              :closable="false"
            />
          </div>
        </div>
        <!-- 风格设置 -->
        <div class="setting-item">
          <h3 class="setting-title">风格设置</h3>
          <!-- 文本和暗标要求 -->
          <div class="sub-setting">
            <h3 class="sub-setting-title">文本和暗标要求</h3>
            <div class="option-cards">
              <div
                v-for="(style, key) in textStyles"
                :key="String(key)"
                class="option-card"
                :class="{ active: textStyleOption === String(key) }"
                @click="textStyleOption = String(key)"
              >
                <div class="option-icon" :class="key">
                  <el-icon v-if="String(key) === 'technical'"
                    ><DataAnalysis
                  /></el-icon>
                  <el-icon v-else-if="String(key) === 'business'"
                    ><Money
                  /></el-icon>
                  <el-icon v-else-if="String(key) === 'custom'"
                    ><Edit
                  /></el-icon>
                </div>
                <div class="option-content">
                  <div class="option-title">{{ style.title }}</div>
                  <span class="option-description">{{
                    style.description
                  }}</span>
                </div>
              </div>
              <div
                class="option-card"
                :class="{ active: textStyleOption === 'custom' }"
                @click="customClick"
              >
                <div class="option-icon custom">
                  <el-icon><Edit /></el-icon>
                </div>
                <div class="option-content">
                  <div class="option-title">自定义风格</div>
                  <span class="option-description"
                    >可根据实际需求自定义语言风格和格式。</span
                  >
                </div>
              </div>
            </div>
          </div>
          <!-- 表格使用量 -->
          <div class="sub-setting">
            <h4 class="sub-setting-title">表格</h4>
            <div class="option-cards">
              <div
                v-for="(option, key) in tableOptions"
                :key="String(key)"
                class="option-card"
                :class="{ active: tableOption === String(key) }"
                @click="tableOption = String(key)"
              >
                <div class="option-icon" :class="key">
                  <el-icon v-if="String(key) === 'none'"><Remove /></el-icon>
                  <el-icon v-else-if="String(key) === 'moderate'"
                    ><Grid
                  /></el-icon>
                  <el-icon v-else-if="String(key) === 'extensive'"
                    ><CopyDocument
                  /></el-icon>
                </div>
                <div class="option-content">
                  <div class="option-title">{{ option.title }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>
      </div>
      <!-- 需求明细 -->
      <div v-else-if="activeStep === 1">
        <h2 class="step-title">需求明细</h2>
        <div class="option-item">
          <el-checkbox
            v-model="enableR1Thinking"
            label="启用R1深度思考"
            size="large"
          />
          <div class="option-description">
            启用后将使用更深层次的思考模式分析需求，生成更全面的标书内容
          </div>
        </div>
        <!-- 上传模式选择 -->
        <div class="setting-item">
          <h3 class="setting-title">上传模式</h3>
          <div class="upload-mode-selector">
            <el-radio-group v-model="uploadMode" size="large">
              <el-radio-button label="file">
                <el-icon><Upload /></el-icon> 上传招标文件
              </el-radio-button>
              <el-radio-button label="paste">
                <el-icon><DocumentCopy /></el-icon> 粘贴项目需求
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
<!-- 文件上传区域 -->
<div v-if="uploadMode === 'file'" class="setting-item">
  <h3 class="setting-title">上传需求文件</h3>
  <el-upload
    class="upload-area"
    action="#"
    :auto-upload="false"
    :on-change="handleFileChange"
    :on-remove="handleFileRemove"
    :file-list="fileList"
    :multiple="false"
    :before-upload="beforeUpload"
    accept=".docx"
    drag
  >
    <el-icon class="el-icon--upload"><Upload /></el-icon>
    <div class="el-upload__text">
      <template> 拖拽文件到此处，或 <em>点击上传</em> </template>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        <div style="color: #409eff; font-weight: 500; margin-bottom: 4px;">
          📄 文件要求：
        </div>
        <div style="color: #666;">
          • 仅支持 .docx 格式文件<br>
          • 文件大小不超过 5MB<br>
          • 建议上传完整的招标文件或需求文档
        </div>
      </div>
    </template>
  </el-upload>
</div>
        <!-- 复制粘贴区域 -->
        <div v-if="uploadMode === 'paste'" class="setting-item">
          <h3 class="setting-title">粘贴需求内容</h3>
          <div class="paste-container">
            <!-- 项目概述 -->
            <div class="paste-section">
              <h4 class="paste-section-title">项目概述</h4>
              <el-input
                v-model="projectOverview"
                type="textarea"
                :rows="6"
                placeholder="请粘贴项目概述、背景和主要需求..."
                class="paste-area"
              />
            </div>
            <!-- 评分要求 -->
            <!--  <div class="paste-section">
              <h4 class="paste-section-title">评分要求</h4>
              <el-input
                v-model="scoringRequirements"
                type="textarea"
                :rows="6"
                placeholder="请粘贴招标文件中的评分标准和要求..."
                class="paste-area"
              />
            </div> -->
          </div>
        </div>
        <!-- 高级选项 -->
        <div class="setting-item">
          <!-- 标书类型 -->
          <div class="sub-setting">
            <h4 class="sub-setting-title">标书类型</h4>
            <div class="option-cards">
              <div
                v-for="(type, key) in tenderTypes"
                :key="String(key)"
                class="option-card"
                :class="{ active: tenderType === String(key) }"
                @click="tenderType = String(key)"
              >
                <div class="option-icon" :class="key">
                  <el-icon v-if="String(key) === 'government'"
                    ><Connection
                  /></el-icon>
                  <el-icon v-else-if="String(key) === 'enterprise'"
                    ><Briefcase
                  /></el-icon>
                  <el-icon v-else-if="String(key) === 'international'"
                    ><Notebook
                  /></el-icon>
                  <el-icon v-else-if="String(key) === 'ppp'"
                    ><Tickets
                  /></el-icon>
                </div>
                <div class="option-content">
                  <div class="option-title">{{ type.title }}</div>
                </div>
              </div>
            </div>
          </div>
          <!-- 服务清单上传 -->
          <!--           <div class="sub-setting">
            <h4 class="sub-setting-title">服务清单上传（可选）</h4>
            <el-upload
              class="service-list-upload"
              action="#"
              :auto-upload="false"
              :on-change="handleServiceListChange"
              :on-remove="handleServiceListRemove"
              :file-list="serviceList"
            >
              <el-button type="primary" plain>
                <el-icon><Upload /></el-icon> 上传服务清单
              </el-button>
              <template #tip>
                <div class="el-upload__tip">上传服务清单可以更准确地生成标书内容</div>
              </template>
            </el-upload>
          </div> -->

          <!-- 引用资料 -->
          <div class="sub-setting">
            <div class="knowledge-base-option">
              <el-checkbox
                v-model="isGenerateKnowledgeBase"
                label="是否关联知识库"
                size="large"
                disabled
              />
            </div>
          </div>

          <!-- 知识库选择 -->
          <!--  <div class="sub-setting">
            <h4 class="sub-setting-title">知识库选择</h4>
            <el-checkbox-group v-model="selectedKnowledgeBases">
              <div class="knowledge-base-cards">
                <div
                  v-for="(kb, key) in knowledgeBases"
                  :key="key"
                  class="knowledge-base-card"
                  :class="{ 'active': selectedKnowledgeBases.includes(key) }"
                  @click="toggleKnowledgeBase(key)"
                >
                  <div class="kb-header">
                    <div class="kb-icon" :class="key">
                      <el-icon v-if="key === 'industry'"><Collection /></el-icon>
                      <el-icon v-else-if="key === 'company'"><Briefcase /></el-icon>
                      <el-icon v-else-if="key === 'legal'"><Document /></el-icon>
                      <el-icon v-else-if="key === 'technical'"><Files /></el-icon>
                    </div>
                    <div class="kb-title">{{ kb.title }}</div>
                  </div>
                  <div class="kb-description">{{ kb.description }}</div>
                </div>
              </div>
            </el-checkbox-group>
          </div> -->
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="goToDirectoryWriting"
            >思考目录</el-button
          >
        </div>
      </div>
      <!-- 目录编写模块 -->
      <div v-else-if="activeStep === 2" class="directory-container">
        <!-- 加载进度弹窗 -->

        <!-- 目录编写区域 - 左右布局 -->
        <div class="directory-content">
          <!-- 左侧卡片区域 - 始终显示 -->
          <div class="directory-sidebar">
            <el-card class="directory-card" v-if="directoryGenerated">
              <el-tabs v-model="activeTab" tab-position="top">
                <el-tab-pane label="评分点" name="score">
                  <el-card class="sidebar-card">
                    <div v-if="scorePoints.length > 0" class="score-points-list">
                      <div
                        v-for="(point, index) in scorePoints"
                        :key="index"
                        class="score-point-item"
                      >
                        <div class="score-point-header">
                          <el-tag size="small">{{
                            point.display_key
                          }}</el-tag>
                        </div>
                        <div class="score-point-content">
                          {{ point.query }}
                        </div>
                      </div>
                    </div>
                    <div v-else class="empty-score-points">
                      <el-empty description="未上传招标文件，无评分点信息" :image-size="80" />
                    </div>
                  </el-card>
                </el-tab-pane>
                <el-tab-pane label="项目概述" name="overview">
                  <el-card class="sidebar-card">
                    <div class="project-overview-content">
                      <p>{{ projectOverview || "暂无项目概述信息" }}</p>
                    </div>
                  </el-card>
                </el-tab-pane>
              </el-tabs>
            </el-card>
          </div>

          <!-- 右侧卡片区域 -->
          <div class="directory-main">
            <!-- 原始目录编写思路 -->
            <el-card
              v-if="
                directoryGenerated &&
                !showDirectoryOptions &&
                !isEditingSelectedPlan
              "
              class="directory-card"
            >
              <template #header>
                <div class="directory-header">
                  <div class="directory-title">
                    <h3>目录编写思路</h3>
                    <el-tooltip
                      content="系统根据需求自动生成的章节结构，您可以根据需要调整"
                      placement="top"
                    >
                      <el-icon><InfoFilled /></el-icon>
                    </el-tooltip>
                  </div>
                  <div class="directory-actions">
                    <div class="directory-stats">
                      <el-tag type="info"
                        >预计全文字数: {{ totalWordCount }}</el-tag
                      >
                      <el-tag type="info"
                        >预计全文页数: {{ totalPageCount }}</el-tag
                      >
                    </div>
                    <el-button
                      type="primary"
                      @click="handleRegenerate"
                      :icon="Refresh"
                      >重新生成</el-button
                    >
                  </div>
                </div>
              </template>

              <!-- 章节列表 -->
              <div class="chapters-list">
                <el-collapse v-model="activeChapters">
                  <el-collapse-item
                    v-for="(chapter, index) in generatedChapters"
                    :key="index"
                    :name="index"
                  >
                    <!-- 章节标题 -->
                    <template #title>
                      <div class="chapter-header">
                        <div class="chapter-title">
                          <span class="chapter-number">{{ index + 1 }}.</span>
                          <span
                            v-if="!chapter.isEditing"
                            @click.stop="editChapter(index)"
                            class="chapter-name"
                            >{{ chapter.chapter }}</span
                          >
                          <el-input
                            v-else
                            v-model="chapter.chapter"
                            placeholder="章节名称"
                            size="small"
                            class="chapter-edit-input"
                            @blur="chapter.isEditing = false"
                            @click.stop
                          />
                        </div>
                        <div class="chapter-info">
                          <el-tag size="small" type="success"
                            >{{ chapter.wordCount }}字</el-tag
                          >
                          <el-tag size="small" type="info"
                            >{{ chapter.pageNumber }}页</el-tag
                          >
                        </div>
                      </div>
                    </template>

                    <!-- 章节内容 -->
                    <div class="chapter-content">
                      <div class="chapter-thought">
                        <div class="thought-header">
                          <h4>编写思路</h4>
                          <el-tooltip
                            content="点击编辑编写思路"
                            placement="top"
                          >
                            <el-icon class="edit-icon"><Edit /></el-icon>
                          </el-tooltip>
                        </div>
                        <el-input
                          v-model="chapter.thoughts"
                          type="textarea"
                          :rows="6"
                          placeholder="请输入本章节的编写思路、要点和关键内容..."
                          class="thought-textarea"
                        />
                      </div>

                      <div class="chapter-actions">
                        <div class="left-actions">
                          <el-button
                            type="primary"
                            plain
                            size="small"
                            @click.stop="addSubChapter(index)"
                          >
                            <el-icon><Plus /></el-icon>添加章节
                          </el-button>
                        </div>
                        <div class="right-actions">
                          <el-button
                            plain
                            size="small"
                            @click.stop="moveChapterUp(index)"
                            :disabled="index === 0"
                          >
                            <el-icon><Top /></el-icon>上移
                          </el-button>
                          <el-button
                            plain
                            size="small"
                            @click.stop="moveChapterDown(index)"
                            :disabled="index === generatedChapters.length - 1"
                          >
                            <el-icon><Bottom /></el-icon>下移
                          </el-button>
                          <el-button
                            type="danger"
                            plain
                            size="small"
                            @click.stop="removeChapter(index)"
                          >
                            <el-icon><Delete /></el-icon>删除
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </el-card>

            <!-- 选中方案的编辑界面 -->
            <el-card
              v-if="!showDirectoryOptions && isEditingSelectedPlan"
              class="directory-card selected-plan-edit"
            >
              <template #header>
                <div class="directory-header">
                  <div class="directory-title">
                    <h3>
                      <el-tag
                        size="small"
                        type="success"
                        class="selected-plan-tag"
                        >已选方案</el-tag
                      >
                        {{
                        directoryOptions[selectedDirectoryIndex]?.title ||
                        "方案编辑"
                      }}
                    </h3>
                    <el-tooltip
                      content="您可以根据需要调整章节结构和内容"
                      placement="top"
                    >
                      <el-icon><InfoFilled /></el-icon>
                    </el-tooltip>
                  </div>
                  <div class="directory-actions">
                    <div class="directory-stats">
                      <el-tag type="info"
                        >预计全文字数: {{ totalWordCount }}</el-tag
                      >
                      <el-tag type="info"
                        >预计全文页数: {{ totalPageCount }}</el-tag
                      >
                    </div>
                    <el-button
                      type="primary"
                      @click="showDirectoryOptions = true"
                      :icon="Refresh"
                      >重新选择</el-button
                    >
                  </div>
                </div>
              </template>

              <!-- 章节列表，使用不同的样式 -->
              <div class="chapters-list selected-plan">
                <el-collapse v-model="activeChapters">
                  <el-collapse-item
                    v-for="(chapter, index) in generatedChapters"
                    :key="index"
                    :name="index"
                  >
                    <!-- 章节标题 -->
                    <template #title>
                      <div class="chapter-header">
                        <div class="chapter-title">
                          <span class="chapter-number">{{ index + 1 }}.</span>
                          <span
                            v-if="!chapter.isEditing"
                            @click.stop="editChapter(index)"
                            class="chapter-name"
                            >{{ chapter.title }}</span
                          >
                          <el-input
                            v-else
                            v-model="chapter.title"
                            placeholder="章节名称"
                            size="small"
                            class="chapter-edit-input"
                            @blur="chapter.isEditing = false"
                            @click.stop
                          />
                        </div>
                        <div class="chapter-info">
                          <el-tag size="small" type="success"
                            >{{ chapter.wordCount }}字</el-tag
                          >
                          <el-tag size="small" type="info"
                            >{{ chapter.pageNumber }}页</el-tag
                          >
                        </div>
                      </div>
                    </template>
                    <!-- 章节内容 -->
                    <div class="chapter-content selected-plan-content">
                      <div class="chapter-thought">
                        <div class="thought-header">
                          <h4>编写思路</h4>
                          <el-tooltip
                            content="点击编辑编写思路"
                            placement="top"
                          >
                            <el-icon class="edit-icon"><Edit /></el-icon>
                          </el-tooltip>
                        </div>
                        <el-input
                          v-model="chapter.thoughts"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入本章节的编写思路、要点和关键内容..."
                          class="thought-textarea"
                        />
                      </div>

                      <!-- 添加章节智能操作按钮 -->
                      <div class="chapter-ai-actions">
                        <el-button
                          size="small"
                          type="success"
                          @click.stop="expandChapter(index)"
                        >
                          <el-icon><Plus /></el-icon> 内容扩充
                        </el-button>
                        <el-button
                          size="small"
                          type="warning"
                          @click.stop="rewriteChapter(index)"
                        >
                          <el-icon><Refresh /></el-icon> 内容重写
                        </el-button>
                      </div>

                      <div class="chapter-actions">
                        <div class="left-actions">
                          <el-button
                            type="primary"
                            plain
                            size="small"
                            @click.stop="addSubChapter(index)"
                            style="color: white !important; -webkit-text-fill-color: white !important;"
                          >
                            <el-icon style="color: white !important; -webkit-text-fill-color: white !important;"><Plus /></el-icon>添加章节
                          </el-button>
                        </div>
                        <div class="right-actions">
                          <el-button
                            plain
                            size="small"
                            @click.stop="moveChapterUp(index)"
                            :disabled="index === 0"
                          >
                            <el-icon><Top /></el-icon>上移
                          </el-button>
                          <el-button
                            plain
                            size="small"
                            @click.stop="moveChapterDown(index)"
                            :disabled="index === generatedChapters.length - 1"
                          >
                            <el-icon><Bottom /></el-icon>下移
                          </el-button>
                          <el-button
                            type="danger"
                            plain
                            size="small"
                            @click.stop="removeChapter(index)"
                            style="color: white !important; -webkit-text-fill-color: white !important;"
                          >
                            <el-icon style="color: white !important; -webkit-text-fill-color: white !important;"><Delete /></el-icon>删除
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </el-card>

            <!-- 目录方案选择 -->
            <el-card v-if="showDirectoryOptions" class="directory-card">
              <template #header>
                <div class="directory-header">
                  <div class="directory-title">
                    <h3>选择目录方案</h3>
                    <el-tooltip
                      content="系统根据您的需求生成了以下几种目录方案，请选择一种适合的方案"
                      placement="top"
                    >
                      <el-icon><InfoFilled /></el-icon>
                    </el-tooltip>
                  </div>
                  <div v-if="selectedDirectoryIndex >= 0" class="selection-tip">
                    <el-tag type="success" effect="dark">
                      <el-icon><Check /></el-icon>
                      已选择方案 {{ selectedDirectoryIndex + 1 }}
                    </el-tag>
                  </div>
                </div>
              </template>

              <div class="directory-options">
                <div
                  v-for="(option, index) in directoryOptions"
                  :key="index"
                  class="directory-option-card"
                  :class="{ selected: selectedDirectoryIndex === index }"
                  @click="selectDirectory(index)"
                  v-loading="catalogLoad"
                >
                  <div class="option-header">
                    <h3>{{ option.title }}</h3>
                  </div>
                  <div class="directory-preview">
                    <!-- 方案预览 -->
                    <div v-for="(chapter, idx) in option.chapters" :key="idx">
                      <div class="chapter-title">{{ chapter.title }}</div>
                      <div
                        v-for="(sub, subIdx) in chapter.subChapters"
                        :key="subIdx"
                        class="sub-chapter"
                        :style="{
                          paddingLeft: getSubChapterIndent(sub) + 'px',
                        }"
                      >
                        {{ sub }}
                      </div>
                    </div>
                  </div>
                  <div class="directory-stats">
                    <el-tag size="small">预计页数: {{ option.pages }}</el-tag>
                    <el-tag size="small" type="success"
                      >预计字数: {{ option.words }}</el-tag
                    >
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <template v-if="isEditingSelectedPlan">
            <el-button
              type="primary"
              @click="startWritingContent"
              class="single-button"
            >
              编写正文
            </el-button>
          </template>

          <template v-else>
            <el-button @click="prevStep">修改需求明细</el-button>
            <el-button
              type="primary"
              v-if="!showDirectoryOptions"
              @click="handleDirectoryButton"
            >
              编写目录
            </el-button>
            <el-button
              type="primary"
              v-if="showDirectoryOptions"
              @click="startWritingContent"
            >
              编写正文
            </el-button>
          </template>
        </div>
        <el-dialog
          v-model="isContentLoading"
          title="加载中"
          width="300px"
          :close-on-click-modal="false"
          :show-close="false"
          :modal="true"
          align-center
          style="text-align: center"
        >
          <el-icon
            class="is-loading"
            style="font-size: 40px; margin-bottom: 16px"
            ><Loading
          /></el-icon>
          <div>正在加载目录内容，请稍候...</div>
        </el-dialog>
      </div>

      <!-- 正文编写模块 -->
      <div v-if="activeStep === 3" class="content-writing">
        <el-tabs
          v-model="activeContentTab"
          type="border-card"
          @tab-click="handleTabChange"
        >
          <el-tab-pane label="目录模式" name="directory">
            <div class="directory-container-writing">
              <!-- 标题和余额信息 -->
              <div class="directory-header">
                <div class="directory-title">
                  <h2>{{ tenderTitle || "标书标题" }}</h2>
                  <el-tag type="info">预计总页数: {{ totalPages }}页</el-tag>
                  <el-tag type="success">预计总字数: {{ totalWords }}字</el-tag>
                </div>
                <div class="user-balance">
                  <el-tooltip effect="dark" placement="left">
                    <template #content>
                      <div>
                        <p>当前余额：{{ userBalance }}元</p>
                        <p>任务费用：{{ taskCost }}元</p>
                        <p>
                          {{ isBalanceSufficient ? "余额充足" : "余额不足" }}
                        </p>
                      </div>
                    </template>
                    <div
                      class="balance-info"
                      :class="{ insufficient: !isBalanceSufficient }"
                    >
                      <el-icon><Wallet /></el-icon>
                      <span>余额：{{ userBalance }}元</span>
                      <el-tag
                        :type="isBalanceSufficient ? 'success' : 'danger'"
                        size="small"
                      >
                        {{ isBalanceSufficient ? "余额充足" : "余额不足" }}
                      </el-tag>
                    </div>
                  </el-tooltip>
                </div>
              </div>

              <!-- 目录树 -->
              <div class="directory-tree">
                <el-tree
                  :data="formattedChapters"
                  node-key="id"
                  default-expand-all
                  :expand-on-click-node="false"
                  @node-click="handleNodeClick"
                >
                  <template #default="{ node: _unusedNode, data }">
                    <div class="custom-tree-node">
                      <div class="node-content">
                            <!--  <span v-if="data.isLeaf" class="status-icon-wrap">
                          <span v-if="data.isGenerate" class="status-icon status-success">
                            <svg viewBox="0 0 24 24" fill="currentColor" width="1em" height="1em">
                              <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" />
                            </svg>
                          </span>
                          <span v-else class="status-icon status-loading">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="1em" height="1em">
                              <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
                            </svg>
                          </span>
                        </span> -->
                        <span class="chapter-number">{{
                          data.chapterNumber
                        }}</span>
                         <span class="chapter-title">{{ data.title }}</span>
                      </div>
                      <!-- 仅在叶子节点显示状态信息和操作按钮 -->
                      <div v-if="data.isLeaf" class="node-info">
                        <div class="node-status-container">
                          <!-- 状态标签 -->
                          <el-tag
                            size="small"
                            :type="getWriteStatus(data).type as any"
                            class="status-tag"
                          >
                            {{ getWriteStatus(data).text }}
                          </el-tag>

                          <!-- 字数和页数信息 -->
                          <div class="count-tags">
                            <el-tag size="small" type="info" class="count-tag">
                              <el-icon><Document /></el-icon>
                              {{ data.pageCount }}页
                            </el-tag>
                            <el-tag size="small" type="info" class="count-tag">
                              <el-icon><Collection /></el-icon>
                              {{ data.wordCount }}字
                            </el-tag>
                          </div>

                          <!-- 余额不足提示 -->
                          <el-tooltip
                            v-if="getWriteStatus(data).showBalance"
                            effect="dark"
                            placement="top"
                          >
                            <template #content>
                              需要余额：{{
                                (data.wordCount * costPerWord).toFixed(2)
                              }}元
                              <br />
                              当前余额：{{ userBalance }}元
                              <br />
                              请及时充值
                            </template>
                            <el-tag
                              type="danger"
                              size="small"
                              class="balance-warning"
                            >
                              <el-icon><Warning /></el-icon>
                              余额不足
                            </el-tag>
                          </el-tooltip>

                          <!-- 预览按钮 -->
                          <el-button
                            link
                            type="primary"
                            @click.stop="previewNode(data)"
                            class="preview-button"
                          >
                            <el-icon><View /></el-icon>
                            预览
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-tree>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="正文模式" name="content">
            <div class="content-writing-layout">
              <!-- 在正文模式下的目录树 -->
              <div
                class="directory-tree-wrapper"
                :style="{ width: treeWidth + 'px' }"
                v-loading="treeLoading"
                element-loading-text="目录加载中..."
              >
                <div class="directory-tree-container">
                  <el-tree
                    ref="contentTreeRef"
                    :data="formattedChapters"
                    node-key="id"
                    default-expand-all
                    :expand-on-click-node="false"
                    highlight-current
                    :current-node-key="selectedNode?.id"
                    @node-click="handleNodeClick"
                    class="directory-tree"
                  >
                    <template #default="{ node: _unusedNode, data }">
                      <div class="tree-node">
                        <span v-if="data.isLeaf" class="status-icon-wrap">
                          <span
                            v-if="data.isGenerate"
                            class="status-icon status-success"
                          >
                            <svg
                              viewBox="0 0 24 24"
                              fill="currentColor"
                              width="1em"
                              height="1em"
                            >
                              <path
                                d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"
                              />
                            </svg>
                          </span>
                          <span v-else class="status-icon status-loading">
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              width="1em"
                              height="1em"
                            >
                              <path
                                d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"
                              />
                            </svg>
                          </span>
                        </span>
                        <span class="chapter-number">{{
                          data.chapterNumber
                        }}</span>
                        <span class="chapter-title">{{ data.title }}</span>
                     </div>
                    </template>
                  </el-tree>
                </div>
                <div class="resize-handle" @mousedown="startResize">
                  <el-icon class="resize-icon"><DArrowRight /></el-icon>
                </div>
              </div>

              <!-- 中间内容编辑区 -->
              <div class="content-main">
                <div class="content-body-wrapper">
                  <!-- 顶部操作栏：节点信息和保存按钮 -->
                  <div class="action-bar">
                    <!-- 左侧节点信息 -->
                    <div class="node-info" v-if="selectedNode">
                      <div class="node-title">
                        <span class="chapter-number">{{
                          selectedNode.chapterNumber
                        }}</span>
                        <span class="chapter-title">{{
                          selectedNode.label
                        }}</span>
                      </div>
                    </div>
                    <!-- 右侧保存按钮 -->
                    <div class="save-button-container">
                      <el-button
                        type="primary"
                        @click="saveContent"
                        :disabled="!isContentChanged"
                      >
                        <el-icon><Check /></el-icon>保存
                      </el-button>
                    </div>
                  </div>

                  <!-- 可编辑内容区 -->
                  <div
                    class="content-body"
                    contenteditable="true"
                    @input="onContentInput"
                    @focus="handleEditorFocus"
                    @blur="handleEditorBlur"
                    @click="handleEditorClick"
                    ref="contentEditor"
                  ></div>
                </div>
                <el-dialog
                  v-model="isContentsLoading"
                  title="加载中"
                  width="300px"
                  :close-on-click-modal="false"
                  :show-close="false"
                  :modal="true"
                  align-center
                  style="text-align: center"
                >
                  <el-icon
                    class="is-loading"
                    style="font-size: 40px; margin-bottom: 16px"
                    ><Loading
                  /></el-icon>
                  <div>AI思考中，预计剩余3分钟</div>
                </el-dialog>
                <!-- 添加弹窗提示 -->
                <el-dialog
                  v-model="isThinkingDialogVisible"
                  title="思考中"
                  width="300px"
                  :close-on-click-modal="false"
                  :modal="true"
                  :show-close="false"
                  align-center
                  class="thinking-dialog"
                >
                  <div class="thinking-content">
                    <el-icon class="is-loading thinking-icon"
                      ><Loading
                    /></el-icon>
                    <div class="thinking-text">正在思考中，请稍后...</div>
                  </div>
                  <template #footer>
                    <div class="dialog-footer">
                      <el-button
                        @click="
                          isThinkingDialogVisible = false;
                          autoClose = true;
                        "
                        >关闭</el-button
                      >
                    </div>
                  </template>
                </el-dialog>
              </div>

                            <!-- 右侧图片素材区 -->
              <!-- <div class="image-search-panel">
                <div class="search-header">
                  <el-input v-model="imageSearch.keyword" placeholder="搜索图片..." clearable @input="debounceSearch">
                    <template #suffix>
                      <el-icon :class="{ 'is-loading': imageSearch.loading }">
                        <Search v-if="!imageSearch.loading" />
                        <Loading v-else />
                      </el-icon>
                    </template>
                  </el-input>
                </div>
                <div class="image-container">
                  <div class="image-list">
                    <div class="image-item" v-for="image in imageSearch.images" :key="image.id">
                      <div class="image-wrapper">
                        <img :src="image.src" :alt="image.title" />
                      </div>
                      <div class="image-info">
                        <div class="image-title" :title="image.title">{{ image.title }}</div>
                        <el-button
                          type="primary"
                          link
                          size="small"
                          class="insert-image-button"
                          @click.stop.prevent="handleInsertImage(image)"
                          :disabled="!canInsertImage"
                          :title="getButtonTooltip"
                        >
                          插入
                        </el-button>
                      </div>
                    </div>
                  </div>

                  <div v-if="imageSearch.loading" class="loading-more">
                    <el-icon class="is-loading"><Loading /></el-icon>
                    <span>加载中...</span>
                  </div>
                </div>
              </div> -->
            </div>
          </el-tab-pane>

          <el-tab-pane label="全文引用" name="references">
            <!-- 引用管理区域 -->
            <div class="references-manager">
              <!-- 引用内容列表 -->
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- 添加固定的底部按钮容器 -->
        <div class="fixed-bottom-bar">
          <el-button
            type="primary"
            size="large"
            @click="downloadBidDocument"
            :disabled="generatingBids.has(biddoc.bid)"
          >
            <el-icon><Download /></el-icon>
            {{
              generatingBids.has(biddoc.bid) ? "标书正在生成中" : "生成完整标书"
            }}
          </el-button>
        </div>
      </div>
    </div>
    <el-dialog
      title="自定义风格"
      v-model="isCustomStyleDialogVisible"
      :close-on-click-modal="false"
      :modal="true"
      :width="'600px'"
      :custom-class="'custom-style-dialog'"
    >
      <template #header>
        <div style="display: flex; align-items: center">
          <el-icon><Edit /></el-icon>
          <span style="margin-left: 8px">自定义风格</span>
        </div>
      </template>
      <el-form :model="customStyleForm" label-width="120px">
        <el-form-item label="风格名字">
          <el-input
            v-model="customStyleForm.name"
            placeholder="请输入风格名字"
          />
        </el-form-item>
        <el-form-item label="风格训练">
          <el-input
            v-model="customStyleForm.training"
            type="textarea"
            placeholder="请输入风格训练内容"
          />
        </el-form-item>
        <el-form-item label="暗标要求">
          <el-input
            v-model="customStyleForm.requirements"
            type="textarea"
            placeholder="请输入暗标要求"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isCustomStyleDialogVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="saveCustomStyle"> 确 定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传进度弹窗 -->
    <el-dialog
      v-model="showUploadDialog"
      width="400px"
      :close-on-click-modal="false"
      :show-close="false"
      :modal="true"
      align-center
      class="upload-dialog"
    >
      <div class="upload-dialog-content">
        <div class="upload-progress">
          <div class="progress-header">
            <span class="progress-title">上传进度</span>
            <span class="progress-percentage">{{ uploadProgress }}%</span>
          </div>
          <el-progress
            :percentage="uploadProgress"
            :stroke-width="10"
            :show-text="false"
            class="progress-bar"
            :color="uploadProgress === 100 ? '#67c23a' : '#409eff'"
          />
          <div class="upload-status">
            <el-icon
              v-if="isUploading && uploadProgress < 100"
              class="uploading-icon"
            >
              <Loading />
            </el-icon>
            <el-icon v-else-if="uploadProgress === 100" class="success-icon">
              <CircleCheck />
            </el-icon>
            <span class="status-text">
              {{
                isUploading && uploadProgress < 100
                  ? "上传中..."
                  : uploadProgress === 100
                  ? "上传完成"
                  : "准备上传"
              }}
            </span>
          </div>
        </div>
      </div>
    </el-dialog>
    <transition name="fade">
      <el-dialog
        v-model="isDirectoryLoading"
        title="加载中"
        width="300px"
        :close-on-click-modal="false"
        :show-close="false"
        :modal="true"
        align-center
        style="text-align: center"
      >
        <el-progress
          :percentage="directoryLoadingProgress"
          :format="(percentage) => `${percentage}%`"
          :status="directoryLoadingStatus as any"
        />
        <div class="loading-text">{{ directoryLoadingText }}</div>
      </el-dialog>
    </transition>
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
    computed,
  watch,
  nextTick,
  onMounted,
  onBeforeUnmount,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  chapterThink,
  getChapterThinkResult,
  detailedTitles,
  getDetailedTitles,
  getCatalogByBid,
  getChildernBidserial,
  getfull,
   parseBidFile,
   createBid,
  getChildrenBidPathId,
  bid_upload,
} from "@/api/bid/catalogue";
import {
  Edit,
  Collection,
  Refresh,
  Plus,
  Top,
  Bottom,
  Delete,
  Check,
  Wallet,
  View,
  Warning,
  Download,
  Search,
  Loading,
  DArrowRight,
  CircleCheck,
  Message,
} from "@element-plus/icons-vue";
import { useDebounceFn } from "@vueuse/core";
import { useModeStore } from "@/store/modules/mode";
import { useTenderStore } from "@/store/modules/tender";
import { cloneDeep, isEqual } from "lodash-es";
import { title } from "process";
const modeStore = useModeStore();
const router = useRouter();
const route = useRoute();
const treeLoading = ref(false);
const selectedNode = ref<{
  id: string;
  label: string;
  content: string;
  isLeaf: boolean;
  pageCount: number;
  wordCount: number;
  chapterNumber: string;
} | null>(null);
/* const Select = (nodeInfo) => {
  // 这里可以添加业务逻辑
  console.log('选中节点信息:', nodeInfo);
  selectedNode.value = {
    label: nodeInfo.data.label,
    content: nodeInfo.data.content,
    isLeaf: nodeInfo.isLeaf
  };
}; */
// const selectedCategory = ref(null);
/* const handleSelect = (item) => {
  selectedCategory.value = item;
};

const compendiumVisible = ref(false); */

const catalogLoad = ref(false);
const tenderStore = useTenderStore();
const activeStep = ref(0);
const tenderTitle = ref("");
const projectOverview = ref("");
const enableR1Thinking = ref(false);
const uploadMode = ref("paste");
const tenderType = ref("government");
// 用store字段替换ref
/* 
const activeStep = tenderStore.activeStep;
const tenderTitle = tenderStore.tenderTitle;
const pageCount = tenderStore.pageCount;
const projectOverview = tenderStore.projectOverview;
const enableR1Thinking = tenderStore.enableR1Thinking;
const uploadMode = tenderStore.uploadMode;
const textStyleOption = tenderStore.textStyleOption;
const tenderType = tenderStore.tenderType;
 */



// nextStep/prevStep直接操作store
const nextStep = async () => {
  if(activeStep.value===0){
    if (!tenderTitle.value?.trim()) {
      ElMessage.error("请输入标书标题！");
      return;
    }
  }
  if (activeStep.value < 3) {
 const res:any = await createBid({
      title: tenderTitle.value,
      style: textStyles[textStyleOption.value]?.title,
      words: wordCount.value,
    });
    if (res.code === 200) {
      biddoc.bid = res.data
    } else {
      ElMessage.error(res.msg || "生成失败，请重试");
      return;
    }
    activeStep.value++;
  }
};

const prevStep = () => {
  if (activeStep.value > 0) {
    activeStep.value--;
    // tenderStore.activeStep=cloneDeep(activeStep.value)
  }
};

const eventSourceInstance = ref<EventSource | null>(null);
const streamedContent = ref(""); // 存储并实时显示流式内容
// --- 2. 封装完整的SSE启动与管理函数 ---

// 在组件中添加一个变量来累积内容
const accumulatedContent = ref("");

 const startStream = (bid: string, path: string) => {
  // a. 清理旧连接
  if (eventSourceInstance.value) {
    eventSourceInstance.value.close();
  }

  // b. 初始化状态
  isContentsLoading.value = true;

  // 重置累积内容
  accumulatedContent.value = "";

  // 添加检查，确保contentEditor.value存在
  if (contentEditor.value) {
    contentEditor.value.innerHTML = "";
  } else {
    console.warn("contentEditor.value 为 null，等待DOM渲染完成");
    // 可以选择延迟执行或使用nextTick
    nextTick(() => {
      if (contentEditor.value) {
        contentEditor.value.innerHTML = "";
      } else {
        console.error("DOM渲染后 contentEditor.value 仍为 null");
      }
    });
  }

  streamedContent.value = ""; // 开始新任务前清空旧内容

  // c. 构造SSE URL
  const sseUrl =
    import.meta.env.VITE_APP_SSE_URL +
    `/document/get_content?bid=${bid}&path_id=${path}`;

  // d. 创建新实例并绑定事件
  const es = new EventSource(sseUrl);
  eventSourceInstance.value = es;

  es.addEventListener("content_chunk", (event) => {
    const data = JSON.parse(event.data);

    // 将新内容添加到累积变量中
    accumulatedContent.value += data.content;

    // 然后更新DOM
    if (contentEditor.value) {
      // 直接设置innerHTML，不使用cloneDeep
      contentEditor.value.innerHTML = accumulatedContent.value;
      console.log("更新内容，当前长度:", accumulatedContent.value.length);
    } else {
      streamedContent.value = accumulatedContent.value;
      console.warn("接收内容时 contentEditor.value 为 null");
    }
  });

  es.addEventListener("status_update", (event) => {
    if (JSON.parse(event.data).status_text === "开始获取内容...") {
      isContentsLoading.value = false;
    }
    if (JSON.parse(event.data).status_text === "标书不存在") {
      isContentsLoading.value = false;
      ElMessage.error('标书不存在！')
    }
     if (JSON.parse(event.data).status_text === "章节尚未生成，请稍后重试") {
      isContentsLoading.value = false;
      ElMessage.info('内容生成中，请耐心等待。。。')
    }
    if (JSON.parse(event.data).status_text === "当前节点不支持预览，请生成全文") {
      isContentsLoading.value = false;
      ElMessage.error('当前节点不支持预览，请生成全文！')
    }
    if (JSON.parse(event.data).status_text === "只支持第1章节预览") {
      isContentsLoading.value = false;
       ElMessage.error('只支持第1章节预览！')
    }


    if (JSON.parse(event.data).status_text === "complete") {
      es.close();
      isContentsLoading.value = false;
      let targetNode = findNodeByNumber(formattedChapters.value, path);
      targetNode.isGenerate = true;
      // 确保最终内容被正确设置
      nextTick(() => {
        if (contentEditor.value) {
          contentEditor.value.innerHTML = accumulatedContent.value;
        }
      });
    }
  });
  es.addEventListener("error", (event:any) => {
    isContentsLoading.value = false;
    ElMessage.error(JSON.parse(event.data).error)

  })

  // d.2. 监听错误
  es.onerror = (error) => {
    console.log(error)
    isContentsLoading.value = false;
    es.close(); // 出错时必须关闭连接
    // ElMessage.error("内容生成失败，请重试。");
  };
}; 
/* const startStream=async (bid: string, path: string)=>{
  try{
    isContentsLoading.value = true;
  const res=await getChildrenBidPathId({
    bid:bid,
    path_id:path
  })
   if (contentEditor.value) {
          contentEditor.value.innerHTML = res.data
        }
 isContentsLoading.value=false
  }catch(res){
    isContentsLoading.value = false
    Message.error('生成失败！')
  }
  finally{
    isContentsLoading.value=false
  }
  
} */

// 页面挂载时自动恢复（首次进入可选reset）
onMounted(async () => {
  console.log(biddoc.bid);
  if (route.query.id && !route.query.is_my_bid) {
    // 使用 nextTick 确保赋值在正确的时机
    await nextTick();
    activeStep.value = cloneDeep(tenderStore.activeStep);
    tenderTitle.value = cloneDeep(tenderStore.tenderTitle);
    pageCount.value = cloneDeep(tenderStore.pageCount);
    wordCount.value = cloneDeep(tenderStore.wordCount);
    projectOverview.value = cloneDeep(tenderStore.projectOverview);
    enableR1Thinking.value = cloneDeep(tenderStore.enableR1Thinking);
    uploadMode.value = cloneDeep(tenderStore.uploadMode);
    textStyleOption.value = cloneDeep(tenderStore.textStyleOption);
    tenderType.value = cloneDeep(tenderStore.tenderType);
    scorePoints.value=cloneDeep(tenderStore.scorePoints);
    generatedChapters.value = cloneDeep(tenderStore.generatedChapters);
    directoryGenerated.value = cloneDeep(tenderStore.directoryGenerated);
    showDirectoryOptions.value = cloneDeep(tenderStore.showDirectoryOptions);
    isEditingSelectedPlan.value = cloneDeep(tenderStore.isEditingSelectedPlan);
    directoryOptions.value = cloneDeep(tenderStore.directoryOptions);
    biddoc.bid = cloneDeep(tenderStore.biddoc.bid);
    formattedChapters.value = cloneDeep(tenderStore.formattedChapters);
    activeContentTab.value = cloneDeep(tenderStore.activeContentTab);
    totalPageCount.value = cloneDeep(tenderStore.totalWordPage.pages);
    totalWordCount.value = cloneDeep(tenderStore.totalWordPage.words);
    selectedOutlineId.value = cloneDeep(tenderStore.selectedOutlineId);
    console.log(selectedOutlineId.value);
    if (activeStep.value == 3) {
      modeStore.setContentMode(true);
      // 查找并选择第一个叶子节点
      const findFirstLeafNode = (nodes: any[]): any => {
        if (!Array.isArray(nodes)) return null;

        for (const node of nodes) {
          if (node.isLeaf) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const leaf = findFirstLeafNode(node.children);
            if (leaf) return leaf;
          }
        }
        return null;
      };
      // 查找并选择第一个叶子节点
      const firstLeafNode = findFirstLeafNode(formattedChapters.value);
      if (firstLeafNode) {
        // 设置当前选中节点
        selectedNode.value = {
          id: firstLeafNode.id,
          label: firstLeafNode.title,
          content: firstLeafNode.content,
          isLeaf: firstLeafNode.isLeaf,
          pageCount: firstLeafNode.pageCount,
          wordCount: firstLeafNode.wordCount,
          chapterNumber: firstLeafNode.chapterNumber,
        };

        // 设置树形控件的当前选中节点
        contentTreeRef.value?.setCurrentKey(firstLeafNode.id);

        // 加载节点内容
        const pathArray = firstLeafNode.chapterNumber
          .split(".")
          .map(Number)
          .join(".");
        console.log(pathArray);
        isContentChanged.value = false;
        /*  isPolling.value = true;
        isFirstPoll.value = true; */

        // 设置当前轮询的节点标识符
        currentPollingNodeId.value = firstLeafNode.id;

        startStream(biddoc.bid, pathArray);
      }
    }
    console.log(tenderStore.directoryOptions);
  }

  // 如需首次进入重置，取消注释下一行
  // tenderStore.reset();
   });
// --- 3. 添加 onBeforeUnmount 清理钩子 ---
onBeforeUnmount(() => {
  if (eventSourceInstance.value) {
    eventSourceInstance.value.close();
  }
});

// 完成/取消时清空store
const finishTender = () => {
  tenderStore.reset();
  router.push("/tender-writing");
};

// 标书页数
const wordsPerPage = 800;
const wordCount = ref(2400);
const pageCount = ref(3);
const updatePageCount = () => {
  pageCount.value = Math.ceil(wordCount.value / wordsPerPage);
};

// 风格设置
const styleOption = ref("professional");

// 文本风格选项
// 文本风格选项
const textStyleOption = ref("technical");
const textStyles = reactive<any>({
  technical: {
    title: "技术风",
    description: "适用于技术方案，突出专业性、逻辑性和技术细节。",
  },
  business: {
    title: "商务风",
    description: "适用于商务标书，强调条理性、规范性和商务表达。",
  },
});

// 表格使用量选项
const tableOption = ref("moderate");
const tableOptions = reactive<any>({
  none: {
    title: "无表格",
  },
  moderate: {
    title: "适量表格",
  },
  extensive: {
    title: "大量表格",
  },
});

// 需求明细

// 文件上传相关
const fileList = ref<any>([]);
const isUploading = ref(false);
const uploadProgress = ref(0);
const showUploadDialog = ref(false);
const fileUrl=ref('')

const handleFileChange = async (file: any) => {
  // 手动调用文件验证
  if (!beforeUpload(file.raw)) {
    // 验证失败，立即从文件列表中移除
    fileList.value = fileList.value.filter(f => f.uid !== file.uid);
    return;
  }

  // 显示上传弹窗
  showUploadDialog.value = true;
  isUploading.value = true;
  uploadProgress.value = 0;

  try {
    const formData = new FormData();
    formData.append("file", file.raw);
    formData.append("know_title", file.name);

    const res = await bid_upload(formData, {
      onUploadProgress: (progressEvent: any) => {
        if (progressEvent.total) {
          uploadProgress.value = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
        }
      },
    });
    
    if (res.code === 200) {
      uploadProgress.value = 100;
      fileUrl.value = res.data?.url;
      
      // 确保文件在列表中显示
      if (!fileList.value.find(f => f.uid === file.uid)) {
        fileList.value.push(file);
      }
      
      uploadMode.value = "paste";

      setTimeout(() => {
        showUploadDialog.value = false;
        ElMessage.success("文件上传成功");
      }, 1500);
    } else {
      showUploadDialog.value = false;
      ElMessage.error("文件上传失败");
      fileList.value = fileList.value.filter(f => f.uid !== file.uid);
    }
  } catch (error) {
    console.error("文件上传失败:", error);
    showUploadDialog.value = false;
    ElMessage.error("文件上传失败");
    fileList.value = fileList.value.filter(f => f.uid !== file.uid);
  } finally {
    isUploading.value = false;
  }
};

const handleFileRemove = (file: any) => {
  const index = fileList.value.indexOf(file);
  if (index !== -1) {
    fileList.value.splice(index, 1);
  }
};

// 自定义风格点击事件
const customClick = () => {
  textStyleOption.value = "custom";
  isCustomStyleDialogVisible.value = true;
  console.log(isCustomStyleDialogVisible.value);
};

// 复制粘贴内容
// const pastedContent = ref('');
const scoringRequirements = ref("");
// R1深度思考
const isGenerateKnowledgeBase = ref(false);
/* const mockTreeData = ref({
  title: '深圳市南山区实验小学地基（桩基）施工项目',
  catalog: [
    {
      chapter: '工程概况及技术参数',
      serial: 1,
      words: 17640,
      pages: 36,
      children: [
        {
          chapter: '项目基本信息',
          serial: 1,
          words: 5880,
          pages: 12,
          children: [
            {
              chapter: '工程名称及地理位置',
              serial: 1,
              words: 1960,
              pages: 4
            },
            {
              chapter: '建设单位与设计单位',
              serial: 2,
              words: 1960,
              pages: 4
            },
            {
              chapter: '工程规模与承包范围',
              serial: 3,
              words: 1960,
              pages: 4
            }
          ]
        }
        // ... 其他章节数据
      ]
    }
    // ... 其他一级章节数据
  ]
}); */
// 标书类型
const tenderTypes = reactive<any>({
  government: {
    title: "政府采购投标",
  },
  enterprise: {
    title: "企业招标投标",
  },
  international: {
    title: "国际项目投标",
  },
  ppp: {
    title: "PPP项目投标",
  },
});
// 服务清单
const serviceList = ref<any>([]);
const handleServiceListChange = (file: any) => {
  serviceList.value.push(file);
};
const handleServiceListRemove = (file: any) => {
  const index = serviceList.value.indexOf(file);
  if (index !== -1) {
    serviceList.value.splice(index, 1);
  }
};

// 引用材料
const referenceList = ref([]);
const handleReferenceChange = (file: any) => {
  referenceList.value.push(file);
};
const handleReferenceRemove = (file: any) => {
  const index = referenceList.value.indexOf(file);
  if (index !== -1) {
    referenceList.value.splice(index, 1);
  }
};

// 引用材料知识库选择
const selectedReferenceKnowledgeBases = ref<string[]>([]);
const toggleReferenceKnowledgeBase = (key: string) => {
  const index = selectedReferenceKnowledgeBases.value.indexOf(key);
  if (index === -1) {
    selectedReferenceKnowledgeBases.value.push(key);
  } else {
    selectedReferenceKnowledgeBases.value.splice(index, 1);
  }
};

// 知识库选择
const selectedKnowledgeBases = ref(["industry", "company"]);
const knowledgeBases = reactive({
  industry: {
    title: "行业知识库",
    description: "包含各行业专业术语、标准和最佳实践",
  },
  company: {
    title: "企业知识库",
    description: "包含公司案例、模板和专有技术",
  },
  legal: {
    title: "法律法规库",
    description: "包含相关法律法规和政策文件",
  },
  technical: {
    title: "技术资料库",
    description: "包含技术规范、标准和方案",
  },
});

const toggleKnowledgeBase = (key: string) => {
  if (selectedKnowledgeBases.value.includes(key)) {
    selectedKnowledgeBases.value = selectedKnowledgeBases.value.filter(
      (kb) => kb !== key
    );
  } else {
    selectedKnowledgeBases.value.push(key);
  }
};

// 自定义风格表单数据
const isCustomStyleDialogVisible = ref(false);
const customStyleForm = reactive({
  name: "",
  training: "",
  requirements: "",
});

const saveCustomStyle = () => {
  // 保存自定义风格的逻辑
  console.log(customStyleForm);
  isCustomStyleDialogVisible.value = false;
};

// 目录生成相关
// const isGeneratingDirectory = ref(false);
const directoryGenerated = ref(false);
// const generatingProgress = ref(0);
const activeChapters = ref([0, 1]); // 默认展开前两个章节

let generatedChapters = ref<any>([
  {
    id: "1",
    chapter: "项目背景与需求分析",
      // wordCount: 2500,
    // pageNumber: 3,
    // thought: '分析项目背景、行业现状和客户需求，突出我方对项目的理解深度',
    isEditing: false,
    content: "",
    subChapters: [],
  },
  // {
  //   id: '2',
  //   title: '技术方案与实施计划',
  //   wordCount: 5000,
  //   pageNumber: 6,
  //   thought: '详细阐述技术架构、实施方法和项目管理计划，展示我方技术实力',
  //   isEditing: false,
  //   content: '',
  //   subChapters: []
  // },
  // {
  //   id: '3',
  //   title: '团队组织与管理',
  //   wordCount: 3000,
  //   pageNumber: 4,
  //   thought: '介绍项目团队结构、人员配置和管理机制，突出团队专业性和经验',
  //   isEditing: false,
  //   content: '',
  //   subChapters: []
  // },
  // {
  //   id: '4',
  //   title: '质量保障与风险管控',
  //   wordCount: 2800,
  //   pageNumber: 3,
  //   thought: '说明质量管理体系和风险应对措施，展示我方项目控制能力',
  //   isEditing: false,
  //   content: '',
  //   subChapters: []
  // }
]);

// 修复评分点类型问题
interface ScorePoint {
  display_key: string;
  query: string;
  type: "primary" | "success" | "warning" | "danger" | "info";
}

// 创建或修改评分点数组
const scorePoints = ref<ScorePoint[]>([]);

const activeTab = ref("score");

/* const totalWordCount = computed(() => {
  const sum = generatedChapters.value.reduce(
    (acc: any, chapter: any) => acc + chapter.wordCount,
    0
  );
  return `${sum} 字`;
}); */

/* const totalPageCount = computed(() => {
  const sum = generatedChapters.value.reduce(
    (acc: any, chapter: any) => acc + chapter.pageNumber,
    0
  );
  return `${sum} 页`;
}); */
const totalWordCount = ref(0);
const totalPageCount = ref(0);

// 将枚举暴露给模板
const DirectoryState = {
  INITIAL: "initial",
  LOADING: "loading",
  BROWSING: "browsing",
  SELECTING: "selecting",
  EDITING: "editing",
};
//全局标书对象
let biddoc = {
  bid: "",
  add_req: "",
};

// 添加一个状态变量跟踪当前目录编写状态
const directoryState = ref<DirectoryState>(DirectoryState.INITIAL);

// 添加必要的变量定义
const showDirectoryOptions = ref(false); // 是否显示目录方案选择
const selectedDirectoryIndex = ref(-1); // 选中的方案索引
let directoryOptions = ref<any>([]); // 目录方案数据
const activeContentTab = ref("directory"); // 正文编写模块的当前标签页

// 添加树组件的引用
const contentTreeRef = ref<any>(null);

// 添加设置当前节点的方法
const setCurrentNode = (nodeId: string) => {
  if (contentTreeRef.value) {
    nextTick(() => {
      contentTreeRef.value.setCurrentKey(nodeId);
    });
  }
};
const lastSuccessfulRequestData = ref<any>(null); // 添加快照变量
// 添加存储选中方案ID的变量
const selectedOutlineId = ref("");
// 进入目录编写界面
const goToDirectoryWriting = async () => {
  // 添加验证逻辑
  if (!tenderTitle.value?.trim()) {
    ElMessage.error("请输入标书标题！");
    return;
  }

  if (!projectOverview.value?.trim()) {
    ElMessage.error("请输入项目需求！");
    return;
  }
  const reqdata = {
    task: "string",
    user_id: "",
    stream: true,
    bid: biddoc?.bid,
    quote: "1111111111",
    style: textStyles[textStyleOption.value]?.title,
    type: tenderTypes[tenderType.value]?.title,
    words: wordCount.value,
    pages: pageCount.value,
    title: tenderTitle.value,
    content_user: projectOverview.value,
    content_str: "",
    isGenerateKnowledgeBase: isGenerateKnowledgeBase.value,
    part: "技术标（技术参数、工艺方案、进度、质量、安全、成本管理措施等）",
    avoid_parts:
      "商务标（如支付条款、财务状况、售后服务、资质证明、合同法务等）",
  }
  const currentRequestData = {
    topic: tenderTitle.value,
    ds: enableR1Thinking.value,
    style: textStyles[textStyleOption.value]?.title,
    type: tenderTypes[tenderType.value]?.title,
    words: wordCount.value,
    pages: pageCount.value,
    title: tenderTitle.value,
    content_user: projectOverview.value,
    isGenerateKnowledgeBase: isGenerateKnowledgeBase.value,
    part: "技术标（技术参数、工艺方案、进度、质量、安全、成本管理措施等）",
    avoid_parts:
      "商务标（如支付条款、财务状况、售后服务、资质证明、合同法务等）",
  };
  // 如果已经生成过目录，且数据没有变化，则直接进入下一步
  if (
    directoryGenerated.value &&
    lastSuccessfulRequestData.value &&
    isEqual(currentRequestData, lastSuccessfulRequestData.value)
  ) {
    activeStep.value = 2;
    return;
  }

  // 显示加载弹窗和进度条
  isDirectoryLoading.value = true;
  directoryLoadingProgress.value = 0;
  directoryLoadingText.value = "正在分析需求...";

  // 动态进度到20%
  animateProgress(20, 1000, () => {
    directoryLoadingText.value = "正在解析招标文件...";
  });
  if(fileUrl.value){
    // 进度到40%
    animateProgress(40, 1000, () => {
      directoryLoadingText.value = "正在分析招标文件内容...";
    });
    
    try {
      let fileRes: any = await parseBidFile({
        bid: biddoc.bid,
        file_url: fileUrl.value,
        user_content:'string'
      });
      scorePoints.value=fileRes.data
      reqdata.content_file= fileRes.data
    } catch (error) {
      console.error('解析招标文件失败:', error);
      handleDirectoryError("解析招标文件失败，请检查文件格式或联系客服");
      return;
    }
  }
  
  // 进度到60%
  animateProgress(60, 1000, () => {
    directoryLoadingText.value = "正在AI思考目录结构...";
  });

try {
  let res: any = await chapterThink(reqdata);

  // 立即保存并验证 bid
  const bid = res.data?.bid;
  if (!bid) {
      handleDirectoryError("AI思考目录时获取任务ID失败，请联系客服");
      return;
  }else{
// 使用异步轮询函数
  async function pollChapterThinkResult(bid, maxAttempts = 24, interval = 5000) {
    for (let attempt = 0; attempt < maxAttempts; attempt++) {
        try {
            let resultRes: any = await getChapterThinkResult(bid);
            if (resultRes?.data) {
                wait_result(resultRes);
                return resultRes; // 成功返回
            }
            // 更新进度提示（可选）
            directoryLoadingText.value = `AI正在思考目录中... (${attempt + 1}/${maxAttempts})`;
            // 等待一段时间再重试
            await new Promise(resolve => setTimeout(resolve, interval));
        } catch (error) {
            console.error('第', attempt + 1, '次轮询失败:', error);
            // 可以继续重试，或者根据错误类型决定是否终止
        }
    }
    throw new Error('轮询超时');
}

// 使用轮询函数
try {
    await pollChapterThinkResult(bid);
} catch (error) {
    handleDirectoryError("AI思考目录时网络请求失败，请联系客服");
}
}
} catch (error) {
  console.error('AI思考目录结构失败:', error);
  handleDirectoryError("AI思考目录结构失败，请联系客服");
}
   
};

// 统一的错误处理函数
function handleDirectoryError(message: string) {
    animateProgress(100, 800, () => {
        directoryLoadingText.value = "生成失败，请重试";
        directoryLoadingStatus.value = "exception";
        ElMessage.info(message);
        setTimeout(() => {
            isDirectoryLoading.value = false;
            activeStep.value = 1;
            directoryLoadingStatus.value = "";
        }, 1500);
    });
}

const wait_result = (res: any) => {
   biddoc.bid = res.data.bid;
    totalWordCount.value = res.data.words;
    totalPageCount.value = res.data.pages;
    console.log(biddoc);
    
    // 进度到85%
    animateProgress(85, 800, () => {
      directoryLoadingText.value = "正在整理目录结构...";
    });
    
    // 添加路由参数
    router.push(
     {
        query: { id: biddoc.bid },
      },
      { replace: true }
    );
    
    // 最终进度到100%
    setTimeout(() => {
      animateProgress(100, 500, () => {
        directoryLoadingText.value = "目录生成完成！";
        directoryLoadingStatus.value = "success";
        setTimeout(() => {
          activeStep.value = 2;
        }, 800);
      });
    }, 500);

    // 延长动画显示时间，确保用户能看到完成状态
    setTimeout(() => {
      isDirectoryLoading.value = false;
      directoryGenerated.value = true;
      showDirectoryOptions.value = false;
      isEditingSelectedPlan.value = false;
      generatedChapters.value = res.data.chapters?.chapters;
      // initDirectoryOptions(res);
      lastSuccessfulRequestData.value = cloneDeep(currentRequestData); // 更新快照
      // 确保 store 中的值被更新
      tenderStore.directoryGenerated = cloneDeep(directoryGenerated.value);
      tenderStore.activeStep = 2;
      tenderStore.tenderTitle = cloneDeep(tenderTitle.value);
      tenderStore.pageCount = cloneDeep(pageCount.value);
      tenderStore.wordCount = cloneDeep(wordCount.value);
       tenderStore.scorePoints=cloneDeep(scorePoints.value)
      tenderStore.projectOverview = cloneDeep(projectOverview.value);
      tenderStore.enableR1Thinking = cloneDeep(enableR1Thinking.value);
      tenderStore.uploadMode = cloneDeep(uploadMode.value);
      tenderStore.textStyleOption = cloneDeep(textStyleOption.value);
      tenderStore.tenderType = cloneDeep(tenderType.value);
      tenderStore.contentMode = true;
      tenderStore.generatedChapters = cloneDeep(generatedChapters.value);
      tenderStore.directoryGenerated = true;
      tenderStore.showDirectoryOptions = false;
      tenderStore.isEditingSelectedPlan = false;
      tenderStore.biddoc = cloneDeep(biddoc);
      tenderStore.totalWordPage = cloneDeep({
        words: totalWordCount.value,
        pages: totalPageCount.value,
      });
      console.log(tenderStore.biddoc.bid);
      console.log(biddoc);
    }, 1000);
}
// 初始化目录方案数据
const initDirectoryOptions = (res: any) => {
  directoryOptions.value = [
    {
      title: "方案一：详细技术导向",
      pages: 35,
      words: 28000,
      chapters: [
        {
          title: "1. 项目概述与需求分析",
          subChapters: ["1.1 项目背景", "1.2 需求分析", "1.3 项目目标"],
          wordCount: 2500,
          pageCount: 3,
        },
        {
          title: "2. 技术方案设计",
          subChapters: ["2.1 系统架构", "2.2 功能模块设计", "2.3 技术特点"],
          wordCount: 3000,
          pageCount: 4,
        },
        {
          title: "3. 实施方案",
          subChapters: ["3.1 实施计划", "3.2 质量保证", "3.3 风险控制"],
          wordCount: 2800,
          pageCount: 3,
        },
      ],
    },
  ];
};
// 递归处理章节及其子章节的函数
const processChapterHierarchy = (
  chapter: any,
  level = 0,
  parentNumber = ""
) => {
  const currentNumber = parentNumber
    ? `${parentNumber}.${chapter.serial}`
    : `${chapter.serial}`;

  const result = {
    title: `${currentNumber}. ${chapter.chapter}`,
    level: level,
    wordCount: chapter.words || 0,
    pageCount: chapter.pages || 0,
    thoughts: chapter.thoughts || "",
    subChapters: [],
  };

  // 处理子章节
  if (
    chapter.children &&
    Array.isArray(chapter.children) &&
    chapter.children.length > 0
  ) {
    chapter.children.forEach((child: any) => {
      // 添加子章节的标题到当前章节的subChapters
      result.subChapters.push(
        `${currentNumber}.${child.serial} ${child.chapter}`
      );

      // 递归处理更深层次的子章节
      if (
        child.children &&
        Array.isArray(child.children) &&
        child.children.length > 0
      ) {
        child.children.forEach((grandChild: any) => {
          result.subChapters.push(
            `${currentNumber}.${child.serial}.${grandChild.serial} ${grandChild.chapter}`
          );
        });
      }
    });
  }

  return result;
};

// 修改transformData函数
const transformData = (rawData: any) => {
  if (!Array.isArray(rawData) || rawData.length === 0) {
    console.error("无效的目录数据结构", rawData);
    return [
      {
        title: "方案一：默认标题",
        pages: totalPages.value || 0,
        words: totalWords.value || 0,
        chapters: [],
      },
    ];
  }

  const plans: any = [];

  rawData.forEach((catalogItem, catalogIndex) => {
    const planTitle = catalogItem.title || `方案${catalogIndex + 1}`;
    const chapters: any = [];

    if (catalogItem.catalog && Array.isArray(catalogItem.catalog)) {
      catalogItem.catalog.forEach((topChapter: any) => {
        // 使用递归函数处理章节层级
        chapters.push(processChapterHierarchy(topChapter, 0));
      });
    }

    plans.push({
      title: `方案${catalogIndex + 1}：${planTitle}`,
      id: catalogItem.outline_id,
      pages: catalogItem.pageCnt || totalPages.value,
      words: catalogItem.preTotalWordCnt || totalWords.value,
      chapters: chapters,
    });
  });

  console.log(plans);
  return plans;
};
// 添加缺失的函数
const addSubChapter = (parentIndex: number) => {
  // 简化处理，创建子章节
  const newChapter: any = {
    id: Math.random().toString(36).substring(2, 9),
    title: `${generatedChapters.value[parentIndex].title} - 子章节`,
    wordCount: 800,
    pageNumber: 1,
    thoughts: "",
    isEditing: true,
    content: "",
    subChapters: [],
  };
  generatedChapters.value.splice(parentIndex + 1, 0, newChapter);
  activeChapters.value.push(parentIndex + 1);
};

const moveChapterUp = (index: number) => {
  if (index > 0) {
    const chapter = generatedChapters.value.splice(index, 1)[0];
    generatedChapters.value.splice(index - 1, 0, chapter);
  }
};

const moveChapterDown = (index: number) => {
  if (index < generatedChapters.value.length - 1) {
    const chapter = generatedChapters.value.splice(index, 1)[0];
    generatedChapters.value.splice(index + 1, 0, chapter);
  }
};

const removeChapter = (index: number) => {
  generatedChapters.value.splice(index, 1);
};

// 添加变量以跟踪是否是从方案选择进入的编辑模式
const isEditingSelectedPlan = ref(false);

// 修改处理"编写目录"/"精编本目录"按钮的逻辑
const handleDirectoryButton = async () => {
  if (!showDirectoryOptions.value) {
    isDirectoryLoading.value = true;
    directoryLoadingProgress.value = 0;
    directoryLoadingText.value = "正在准备生成目录...";
    directoryLoadingStatus.value = ""; // 重置状态

    try {
      // 动态进度到30%
      animateProgress(30, 1000, () => {
        directoryLoadingText.value = "正在分析标书结构...";
      });
      let params = {
        user_id: "admin",
        bid: biddoc.bid,
        words_per_title: 20,
        words_per_page: 600,
      };

      // 进度到70%
      animateProgress(70, 1200, () => {
        directoryLoadingText.value = "正在生成详细目录...";
      });

       await detailedTitles(params);
      async function pollChapterThinkResult(bid, maxAttempts = 24, interval = 5000) {
          for (let attempt = 0; attempt < maxAttempts; attempt++) {
              try {
                  let resData: any = await getDetailedTitles(bid);
                  if (resData?.data) {
                      return resData; // 成功返回
                  }
                  directoryLoadingText.value = `目录生成中... (${attempt + 1}/${maxAttempts})`;
                  // 等待一段时间再重试
                  await new Promise(resolve => setTimeout(resolve, interval));
              } catch (error) {
                  console.error('第', attempt + 1, '次轮询失败:', error);
                  // 可以继续重试，或者根据错误类型决定是否终止
              }
          }
          throw new Error('轮询超时');
    }
    let res: any;
    try {
       res = await pollChapterThinkResult(params.bid);
    } catch (error) {
        handleDirectoryError("AI生成目录时网络请求失败，请联系客服");
    }
      // 最终进度到100%
      animateProgress(100, 600, () => {
        directoryLoadingText.value = "目录生成完成";
        directoryLoadingStatus.value = "success";
      });

      directoryOptions.value = [];
      directoryOptions.value = cloneDeep(transformData(res?.data.outline_list));
      showDirectoryOptions.value = true;
      isEditingSelectedPlan.value = false;
      tenderStore.showDirectoryOptions = true;
      tenderStore.isEditingSelectedPlan = false;
      tenderStore.directoryGenerated = true;
      tenderStore.activeStep = 2;
      tenderStore.tenderTitle = cloneDeep(tenderTitle.value);
      tenderStore.pageCount = cloneDeep(pageCount.value);
      tenderStore.wordCount = cloneDeep(wordCount.value);
      tenderStore.projectOverview = cloneDeep(projectOverview.value);
      tenderStore.enableR1Thinking = cloneDeep(enableR1Thinking.value);
      tenderStore.uploadMode = cloneDeep(uploadMode.value);
      tenderStore.textStyleOption = cloneDeep(textStyleOption.value);
      tenderStore.tenderType = cloneDeep(tenderType.value);
      tenderStore.directoryOptions = cloneDeep(directoryOptions.value);
      tenderStore.biddoc = cloneDeep(biddoc);
      tenderStore.totalWordPage = cloneDeep({
        words: totalWordCount.value,
        pages: totalPageCount.value,
      });
      biddoc.bid = cloneDeep(biddoc.bid);
      console.log(tenderStore.directoryOptions);
      // 延迟关闭加载状态
      setTimeout(() => {
        isDirectoryLoading.value = false;
        directoryLoadingStatus.value = ""; // 重置状态
      }, 1000);
    } catch (error) {
      console.error("生成目录失败:", error);
      // 错误时也用动画效果
      animateProgress(100, 600, () => {
        directoryLoadingText.value = "生成失败，请重试";
        directoryLoadingStatus.value = "exception";
        ElMessage.error("生成目录失败，请重试");
      });

      // 延迟关闭加载状态，让用户能看到错误状态
      setTimeout(() => {
        isDirectoryLoading.value = false;
        directoryLoadingStatus.value = ""; // 重置状态
      }, 1500);
    }
  } else if (selectedDirectoryIndex.value >= 0) {
    showDirectoryOptions.value = false;
    isEditingSelectedPlan.value = true;
  } else {
    ElMessage.info("请先选择一个目录方案");
  }
};

  const findNodeByNumber = (nodes: any[], targetNumber: string): any => {
    if (!Array.isArray(nodes)) return null;
    for (const node of nodes) {
      if (node.chapterNumber === targetNumber) {
        return node;
      }
      if (node.children) {
        const found = findNodeByNumber(node.children, targetNumber);
        if (found) return found;
      }
    }
    return null;
  };

// 选择目录方案
const selectDirectory = (index: number) => {
  // 如果点击的是当前已选中的方案，则取消选中
  if (selectedDirectoryIndex.value === index) {
    selectedDirectoryIndex.value = -1;
    selectedOutlineId.value = ""; // 清空选中的方案ID
    console.log("取消选择方案");
    // 清空编辑区的数据
    generatedChapters.value = [];
    return;
  }

  // 标记选中的方案
  selectedDirectoryIndex.value = index;
  // 存储选中方案的ID
  selectedOutlineId.value = directoryOptions.value[index].id || "";
  console.log("选择方案:", index, "方案ID:", selectedOutlineId.value);

  // 在 store 中也存储选中的方案ID
  tenderStore.selectedOutlineId = cloneDeep(selectedOutlineId.value);
  console.log(tenderStore);

  // 将选中的方案数据复制到编辑区，保留层级信息
  const selectedOption = directoryOptions.value[index];
  generatedChapters.value = selectedOption.chapters.map((chapter: any) => ({
    id: Math.random().toString(36).substring(2, 9),
    title: chapter.title,
    wordCount: chapter.wordCount,
    pageNumber: chapter.pageCount,
    thoughts: chapter.thoughts,
    isEditing: false,
    content: "",
    level: chapter.level || 0, // 保存层级信息
    subChapters: chapter.subChapters || [],
  }));
};

// 编辑章节
const editChapter = (index: number) => {
  generatedChapters.value[index].isEditing = true;
};
// 重新生成目录
const handleRegenerate = () => {
  goToDirectoryWriting();
  // isGeneratingDirectory.value = true;
  // showDirectoryOptions.value = true;
};
const isThinking = ref(false);
const autoClose = ref(false);
const isThinkingDialogVisible = ref(false);
// 重构轮询函数
// const pollContent = async (pathArray: any, nodeId: string) => {
// 根据子章节层级计算缩进
const getSubChapterIndent = (subChapter: string) => {
  // 计算子章节的层级深度（通过计算点的数量）
  const dotCount = (subChapter.match(/\./g) || []).length;
  // 基础缩进为10px，每增加一级增加10px
  return 20 * dotCount;
};
//   // 调试日志
//   console.log(
//     "pollContent called, currentPollingNodeId.value:",
//     currentPollingNodeId.value,
//     "nodeId:",
//     nodeId
//   );
//   // 如果已经停止轮询，直接返回
//   if (!isPolling.value) {
//     console.log("轮询已停止，直接返回");
//     return;
//   }

//   // 修改节点检查逻辑：只有当 currentPollingNodeId.value 不为 null 时才进行比较
//   if (
//     currentPollingNodeId.value !== null &&
//     currentPollingNodeId.value !== nodeId
//   ) {
//     console.log("节点已切换，忽略当前轮询");
//     return;
//   }

//   // 创建新的 AbortController
//   currentAbortController = new AbortController();

//   // 如果是第一次轮询，显示加载动画
//   if (isFirstPoll.value) {
//     isContentsLoading.value = true;
//   }

//   const params = {
//     doc_id: biddoc.bid,
//     office_ws: pathArray,
//   };

//   try {
//     // 检查请求是否已被取消
//     if (currentAbortController?.signal?.aborted) {
//       console.log("请求已被取消");
//       return;
//     }

//     const res: any = await getChildernBidserial(params);

//     // 再次检查请求是否已被取消
//     if (currentAbortController?.signal?.aborted) {
//       console.log("请求已被取消，忽略响应");
//       return;
//     }

//     // 检查节点是否仍然是当前轮询的节点
//     if (
//       currentPollingNodeId.value !== nodeId &&
//       currentPollingNodeId.value !== null
//     ) {
//       console.log("节点已切换，忽略响应");
//       return;
//     }

//     // 如果是第一次轮询，接口返回后关闭加载动画
//     if (isFirstPoll.value) {
//       isContentsLoading.value = false;
//       isFirstPoll.value = false;
//     }
//     console.log(isThinking.value, isThinkingDialogVisible.value);
//     // 处理接口返回状态
//     if (res.status === "fail") {
//       if (!isThinking.value) {
//         isThinking.value = true;
//       }
//       isThinkingDialogVisible.value = true;
//     } else if (res.status === "success") {
//       if (isThinking.value) {
//         isThinking.value = false;
//       }
//       isThinkingDialogVisible.value = false;
//     }
//     if (res.code === 200) {
//       // 再次检查节点是否仍然是当前轮询的节点
//       if (
//         currentPollingNodeId.value !== nodeId &&
//         currentPollingNodeId.value !== null
//       ) {
//         console.log("节点已切换，忽略响应");
//         return;
//       }

//       // 如果有新的内容
//       if (res.data && res.data !== "") {
//         // 获取当前所有内容的长度
//         const currentContentLength = contentLines.value.join("").length;

//         // 如果新内容长度大于当前内容长度，说明有新内容
//         if (res.data.length > currentContentLength) {
//           console.log(222);
//           // 只添加新增的部分
//           const newContent = res.data.slice(currentContentLength);
//           contentLines.value.push(newContent);

//           // 更新最后内容更新时间
//           lastContentUpdateTime.value = Date.now();
//           console.log(contentLines.value);
//           console.log(contentEditor.value);
//           // 处理表格样式并更新编辑器内容
//           if (contentEditor.value) {
//             const processedContent = processTableStyles(
//               contentLines.value.join("")
//             ); // 直接join，不加<br>
//             contentEditor.value.innerHTML = processedContent;

//             // 添加自动滚动到最新内容
//             /*  nextTick(() => {
//               const contentBodyWrapper = document.querySelector('.content-body');
//               if (contentBodyWrapper) {
//                 contentBodyWrapper.scrollTop = contentBodyWrapper.scrollHeight;
//               }
//             }); */
//           }
//         }

//         // 检查是否超过15秒没有新内容
//         const currentTime = Date.now();
//         if (currentTime - lastContentUpdateTime.value > 30000) {
//           isPolling.value = false;
//           console.log(333);
//           if (pollTimer) {
//             clearTimeout(pollTimer);
//             pollTimer = null;
//           }

//           // 更新节点内容
//           selectedNodeContent.value = {
//             content: contentLines.value.join(""),
//           };
//         } else if (isPolling.value && currentPollingNodeId.value === nodeId) {
//           // 如果还在轮询且节点没有切换，继续轮询
//           if (
//             currentAbortController &&
//             !currentAbortController.signal.aborted
//           ) {
//             pollTimer = setTimeout(() => pollContent(pathArray, nodeId), 1000);
//           }
//         }
//       } else if (isPolling.value && currentPollingNodeId.value === nodeId) {
//         // 如果还在轮询且节点没有切换，继续轮询
//         if (currentAbortController && !currentAbortController.signal.aborted) {
//           pollTimer = setTimeout(() => pollContent(pathArray, nodeId), 1000);
//         }
//       }
//     } else if (isPolling.value && currentPollingNodeId.value === nodeId) {
//       // 如果还在轮询且节点没有切换，继续轮询
//       if (currentAbortController && !currentAbortController.signal.aborted) {
//         pollTimer = setTimeout(() => pollContent(pathArray, nodeId), 1000);
//       }
//     }
//   } catch (error: any) {
//     // 检查是否是取消请求导致的错误
//     if (
//       error.name === "AbortError" ||
//       (currentAbortController && currentAbortController.signal.aborted)
//     ) {
//       console.log("请求已被取消");
//       return;
//     }

//     // 检查节点是否仍然是当前轮询的节点
//     if (
//       currentPollingNodeId.value !== nodeId &&
//       currentPollingNodeId.value !== null
//     ) {
//       console.log("节点已切换，忽略响应");
//       return;
//     }

//     isContentsLoading.value = false;
//     isFirstPoll.value = false;
//     console.error("获取内容失败:", error);
//     isPolling.value = false;
//     if (pollTimer) {
//       clearTimeout(pollTimer);
//       pollTimer = null;
//     }
//   }
// };
const isContentsLoading = ref(false);
const formatChapter: any = (chapters: any[], parentNumber = "") => {
    if (!Array.isArray(chapters)) {
      console.error("Invalid chapters data:", chapters);
      return [];
    }

    return chapters.map((chapter, index) => {
      const currentNumber = parentNumber
        ? `${parentNumber}.${index + 1}`
        : `${chapter.serial}`;
      return {
        id: `${currentNumber}`,
        title: chapter.chapter,
        wordCount: chapter.words || 0,
        pageCount: chapter.pages || 0,
        chapterNumber: currentNumber,
        content: null,
        isLeaf: !chapter.children || chapter.children.length === 0,
        children: chapter.children
          ? formatChapter(chapter.children, currentNumber)
          : undefined,
      };
    });
  };
// 进入正文编写模块
const startWritingContent = async () => {
  if (selectedDirectoryIndex.value < 0) {
    ElMessage.primary("请先选择一个方案！");
  } else {
    try {
      treeLoading.value = true; // 加载前
      isContentLoading.value = true;

      // 格式化章节数据的函数保持不变
   
      let catalogData = null;
      // 只有在有bid的情况下才请求接口
      if (biddoc.bid) {
        const res = await getCatalogByBid({
          doc_id: biddoc.bid,
          outline_id: selectedOutlineId.value,
        });

        if (!res.data) {
          console.warn("获取目录数据失败");
        } else if (res?.data) {
          catalogData = res.data?.outline?.catalog;
          totalPages.value = res.data?.total_page;
          totalWords.value = res.data?.total_words;
        }
        setCateTimer()
        await getfull({
          outline_id: selectedOutlineId.value || "string",
          user_id: "string",
          bid: biddoc.bid,
          version: "ver_0000",
          limit: -1,
        });
      }
      // 如果接口请求失败或没有bid，使用mock数据
      /* if (!catalogData) {
        catalogData = mockChaptersData.value;
      } */

      // 检查数据有效性
      if (!catalogData || !catalogData) {
        throw new Error("目录数据无效");
      }

      // 处理章节数据
      formattedChapters.value = formatChapter(catalogData);

      // 切换到正文模式
      activeStep.value = 3;
      activeContentTab.value = "content";
      modeStore.setContentMode(true);
      tenderStore.activeStep = 3;
      emit("update:mode", "content");
      tenderStore.directoryGenerated = cloneDeep(directoryGenerated.value);
      tenderStore.showDirectoryOptions = cloneDeep(showDirectoryOptions.value);
      tenderStore.isEditingSelectedPlan = cloneDeep(
        isEditingSelectedPlan.value
      );
      tenderStore.generatedChapters = cloneDeep(generatedChapters.value);
      tenderStore.biddoc = cloneDeep(biddoc);
      tenderStore.pageCount = cloneDeep(pageCount.value);
      tenderStore.wordCount = cloneDeep(wordCount.value);
      tenderStore.projectOverview = cloneDeep(projectOverview.value);
      tenderStore.enableR1Thinking = cloneDeep(enableR1Thinking.value);
      tenderStore.uploadMode = cloneDeep(uploadMode.value);
      tenderStore.textStyleOption = cloneDeep(textStyleOption.value);
      tenderStore.directoryOptions = cloneDeep(directoryOptions.value);
      tenderStore.tenderType = cloneDeep(tenderType.value);
      tenderStore.biddoc.bid = cloneDeep(biddoc.bid);
      tenderStore.formattedChapters = cloneDeep(formattedChapters.value);
      tenderStore.activeContentTab = cloneDeep(activeContentTab.value);

      // 等待DOM更新
      await nextTick();

      // 查找并选择第一个叶子节点
      const findFirstLeafNode = (nodes: any[]): any => {
        if (!Array.isArray(nodes)) return null;

        for (const node of nodes) {
          if (node.isLeaf) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const leaf = findFirstLeafNode(node.children);
            if (leaf) return leaf;
          }
        }
        return null;
      };

      const firstLeafNode = findFirstLeafNode(formattedChapters.value);
      if (firstLeafNode) {
        // 设置当前选中节点
        selectedNode.value = {
          id: firstLeafNode.id,
          label: firstLeafNode.title,
          content: firstLeafNode.content,
          isLeaf: firstLeafNode.isLeaf,
          pageCount: firstLeafNode.pageCount,
          wordCount: firstLeafNode.wordCount,
          chapterNumber: firstLeafNode.chapterNumber,
        };

        // 设置树形控件的当前选中节点
        contentTreeRef.value?.setCurrentKey(firstLeafNode.id);

        // 加载节点内容
        const pathArray = firstLeafNode.chapterNumber
          .split(".")
          .map(Number)
          .join(".");
        treeLoading.value = false; // 加载后
        isContentChanged.value = false;
        /*  isPolling.value = true;
        isFirstPoll.value = true; */

        // 设置当前轮询的节点标识符
        currentPollingNodeId.value = firstLeafNode.id;

        startStream(biddoc.bid, pathArray);
      }
    } catch (error) {
      isContentsLoading.value = false;
      console.error("开始编写正文时出错:", error);
      ElMessage.error("开始编写正文时出错，请检查目录数据是否完整");
    } finally {
      isContentLoading.value = false;
    }
  }
};

/* // 对树形结构中的章节进行编辑
const editChapterInTree = (data: any) => {
  // 找到对应章节并设置为编辑模式
  const chapter = generatedChapters.value.find((ch) => ch.id === data.id);
  if (chapter) {
    chapter.isEditing = true;
  }
}; */
// 初始化目录状态
const resetDirectoryState = () => {
  showDirectoryOptions.value = false;
  directoryGenerated.value = false;
  selectedDirectoryIndex.value = -1;
};
// 添加新的函数
/* const addNewChapter = () => {
  const newChapter = {
    id: Math.random().toString(36).substring(2, 9),
    title: `新章节 ${generatedChapters.value.length + 1}`,
    wordCount: 1000,
    pageNumber: 1,
    thought: '',
    isEditing: true,
    content: '',
    subChapters: []
  };
  generatedChapters.value.push(newChapter);
  activeChapters.value.push(generatedChapters.value.length - 1);
}; */
// 添加章节扩充功能
const expandChapter = (index: number) => {
  // 使用AI扩充章节内容
  ElMessage.success(
    `正在为"${generatedChapters.value[index].title}"生成更丰富的内容...`
  );
  // 模拟AI扩充过程
  setTimeout(() => {
    const chapter = generatedChapters.value[index];
    // 扩充章节内容
    chapter.thought =
      chapter.thought +
      "\n\n扩充内容：本章节可以进一步细化以下方面：\n1. 详细阐述技术架构的先进性和适用性\n2. 补充实现方案的可行性分析\n3. 增加与同类产品的对比优势";
    // 增加字数和页数
    chapter.wordCount = Math.round(chapter.wordCount * 1.3);
    chapter.pageNumber = Math.round(chapter.pageNumber * 1.3);

    ElMessage.success("内容扩充完成!");
  }, 1500);
};
// 添加章节重写功能
const rewriteChapter = (index: number) => {
  // 使用AI重写章节内容
  ElMessage.success(
    `正在为"${generatedChapters.value[index].title}"重新生成内容...`
  );

  // 模拟AI重写过程
  setTimeout(() => {
    const chapter = generatedChapters.value[index];
    // 记录原标题
    // const originalTitle = chapter.title;

    // 重写章节内容
    chapter.thought =
      "重写后的内容：本章节将从创新视角出发，通过数据驱动和案例支持的方式，展现我方解决方案的独特价值和竞争优势。重点阐述方案的可扩展性和未来发展空间。";

    ElMessage.success("内容重写完成!");
  }, 1500);
};
// 修改计算总数的函数
/* const calculateTotals = (data: any): { pages: number; words: number } => {
  if (!data || !data.catalog || !Array.isArray(data.catalog)) {
    return { pages: 0, words: 0 };
  }

  const processNode = (node: any): { pages: number; words: number } => {
    let total = {
      pages: node.pages || 0,
      words: node.words || 0
    };

    if (node.children && Array.isArray(node.children)) {
      node.children.forEach((child: any) => {
        const childTotals = processNode(child);
        total.pages += childTotals.pages;
        total.words += childTotals.words;
      });
    }

    return total;
  };

  return data.catalog.reduce(
    (acc: any, chapter: any) => {
      const chapterTotals = processNode(chapter);
      return {
        pages: acc.pages + chapterTotals.pages,
        words: acc.words + chapterTotals.words
      };
    },
    { pages: 0, words: 0 }
  );
}; */
const totalPages = ref(0);
const totalWords = ref(0);
// 修改计算属性
/* const totalPages = computed(() => {
  if (!mockChaptersData.value) {
    return 0;
  }
  return calculateTotals(mockChaptersData.value).pages;
});

const totalWords = computed(() => {
  if (!mockChaptersData.value) {
    return 0;
  }
  return calculateTotals(mockChaptersData.value).words;
});
 */
// Mock用户余额数据
const mockUserBalance = {
  balance: 1000,
  taskCost: 800,
  isBalanceSufficient: true,
};
// 使用computed属性格式化章节数据
const formattedChapters = ref<any[]>([]);
// 用户余额相关
const userBalance = ref(mockUserBalance.balance);
const taskCost = ref(mockUserBalance.taskCost);
const isBalanceSufficient = ref(mockUserBalance.isBalanceSufficient);
// 添加新的状态变量
const isContentLoading = ref(false);
/* const contentLoadingProgress = ref(0);
const contentLoadingText = ref('正在生成内容...'); */
const contentLines = ref<string[]>([]);
// 添加一个变量记录最后一次内容更新的时间
let lastContentUpdateTime = ref<number>(0);
// 添加首次轮询标志
const isFirstPoll = ref(false);
// 添加当前轮询的节点标识符
const currentPollingNodeId = ref<any>(null);
// 处理节点点击
const handleNodeClick = async (node: any) => {
  // 确保设置完整的节点信息
  selectedNode.value = {
    id: node.id,
    label: node.title,
    content: node.content,
    isLeaf: node.isLeaf,
    pageCount: node.pageCount,
    wordCount: node.wordCount,
    chapterNumber: node.chapterNumber,
  };
  if (isContentChanged.value) {
    const confirm = await ElMessageBox.confirm(
      "当前内容有未保存的更改，是否保存？",
      "提示",
      {
        confirmButtonText: "保存",
        cancelButtonText: "不保存",
        type: "warning",
      }
    ).catch(() => false);

    if (confirm === "confirm") {
      isContentChanged.value = false;
      await saveContent();
    } else if (confirm === "cancel") {
      isContentChanged.value = false;
    } else {
      isContentChanged.value = false;
    }
  }

  // 加载新节点内容
  if (node.isLeaf) {
    try {
      // 强制停止之前的轮询
      if (eventSourceInstance.value) {
        eventSourceInstance.value.close();
      }

      // 重置所有状态
      contentLines.value = [];
      contentEditor.value.innerHTML = "";
      const pathArray = node.chapterNumber.split(".").map(Number).join(".");
      isContentChanged.value = false;
      /* isPolling.value = true;
      isFirstPoll.value = true; */

      // 设置当前轮询的节点标识符
      currentPollingNodeId.value = node.id;

      startStream(biddoc.bid, pathArray);
    } catch (error) {
      console.error("处理节点点击时出错:", error);
      ElMessage.error("加载内容时出错");
    }
  }
};
// 添加预览模式标志
const isPreviewMode = ref(false);
// 目录模式下的节点点击处理
const previewNode = async (node: any) => {
  // 设置预览模式标志
  isPreviewMode.value = true;

  // 强制停止之前的轮询
  if (eventSourceInstance.value) {
    eventSourceInstance.value.close();
  }
  // 切换到正文模式
  activeStep.value = 3;
  activeContentTab.value = "content";
  console.log(activeContentTab.value);
  modeStore.setContentMode(activeContentTab.value === "content");
  emit("update:mode", "content");
  isPolling.value = true;
  contentLines.value = []; // 清空之前的内容
  const pathArray = node.chapterNumber.split(".").map(Number).join(".");
  isContentChanged.value = false;
    // isFirstPoll.value = true;

  // 设置当前轮询的节点标识符
  // currentPollingNodeId.value = node.id;

  // 开始轮询请求
  startStream(biddoc.bid, pathArray);

  // 等待DOM更新
  await nextTick();
  // 查找并选择对应的节点


  const targetNode = findNodeByNumber(
    formattedChapters.value,
    node.chapterNumber
  );
  if (targetNode) {
    contentTreeRef.value?.setCurrentKey(targetNode.id);
  }
};
// 添加一个轮询定时器的引用
let pollTimer: NodeJS.Timeout | null = null;
// 添加当前请求的 AbortController
let currentAbortController: AbortController | null = null;

// 修改停止轮询的函数
/* const stopPolling = () => {
  isPolling.value = false;
  currentPollingNodeId.value = null; // 重置节点标识符

  // 取消当前请求
  if (currentAbortController) {
    currentAbortController.abort();
    currentAbortController = null;
  }

  if (pollTimer) {
    clearTimeout(pollTimer);
    pollTimer = null;
  }

  // 重置所有相关状态
  isContentsLoading.value = false;
  isFirstPoll.value = true;
  contentLines.value = [];
  if (contentEditor.value) {
    contentEditor.value.innerHTML = "";
  }
};
 */
// 在组件卸载时停止轮询
onBeforeUnmount(() => {
  if (eventSourceInstance.value) {
    eventSourceInstance.value.close();
  }
});
// 监听标签页切换
watch(activeContentTab, (newVal) => {
  if (newVal !== "content") {
    if (eventSourceInstance.value) {
      eventSourceInstance.value.close();
    }
  }
});

// 添加监听器
watch(autoClose, (newVal) => {
  if (newVal) {
    // 当弹窗关闭时
    if (eventSourceInstance.value) {
      eventSourceInstance.value.close();
    }
    autoClose.value = false;
  }
});
// 保存内容
const saveContent = async () => {
  if (!selectedNode.value) {
    ElMessage.warning("请先选择要保存的章节");
    return;
  }

  try {
    // 保存逻辑...
    await saveNodeContent(selectedNode.value);
    // 保存成功后重置状态
    isContentChanged.value = false;
    ElMessage.success("保存成功");
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败，请重试");
  }
};
// 监听内容输入
const editableContent = ref("");
// 监听内容失焦
/* const onContentBlur = (e: Event) => {
  editableContent.value = (e.target as HTMLElement).innerHTML;
}; */
// 检查内容是否变化
const isContentChanged = ref(false);
// 内容编辑器引用
const contentEditor = ref<HTMLElement | null>(null);
// 上次保存的内容
const lastSavedContent = ref("");
// 页面离开时提醒
const beforeUnloadHandler = (e: BeforeUnloadEvent) => {
  if (isContentChanged.value) {
    e.preventDefault();
    e.returnValue = "";
    return "";
  }
};
window.addEventListener("beforeunload", beforeUnloadHandler);
onBeforeUnmount(() => {
  window.removeEventListener("beforeunload", beforeUnloadHandler);
});
// 存储选中节点的内容
const selectedNodeContent = ref(null);
// const currentChapterContent = ref(null);
// 只在切换节点时赋值
watch(selectedNodeContent, (val: any) => {
  if (val) {
    // 重置编辑状态
    editableContent.value = val.content || "";
    lastSavedContent.value = val.content || "";
    nextTick(() => {
      if (contentEditor.value) {
        contentEditor.value.innerHTML = val.content || "";
      }
    });
  }
});
/* const isContentLoading = ref(false);
const contentLoadingProgress = ref(0);
const contentLoadingText = ref('正在生成内容...');
const contentLines = ref<string[]>([]);
 */
// Mock 图片数据库
/* const mockImageDatabase = [
  {
    id: '1',
    src: 'https://picsum.photos/300/200?random=1',
    title: '施工现场图1',
    width: 300,
    height: 200,
    thumbnailUrl: 'https://picsum.photos/300/200?random=1',
    keywords: ['施工', '现场', '工地']
  },
  {
    id: '2',
    src: 'https://picsum.photos/300/200?random=2',
    title: '设备安装图2',
    width: 300,
    height: 200,
    thumbnailUrl: 'https://picsum.photos/300/200?random=2',
    keywords: ['设备', '安装', '机械']
  },
  {
    id: '3',
    src: 'https://picsum.photos/300/200?random=3',
    title: '工程规划图3',
    width: 300,
    height: 200,
    thumbnailUrl: 'https://picsum.photos/300/200?random=3',
    keywords: ['规划', '图纸', '设计']
  },
  {
    id: '4',
    src: 'https://picsum.photos/300/200?random=4',
    title: '施工进度图4',
    width: 300,
    height: 200,
    thumbnailUrl: 'https://picsum.photos/300/200?random=4',
    keywords: ['进度', '施工', '计划']
  },
  {
    id: '5',
    src: 'https://picsum.photos/300/200?random=5',
    title: '安全防护图5',
    width: 300,
    height: 200,
    thumbnailUrl: 'https://picsum.photos/300/200?random=5',
    keywords: ['安全', '防护', '施工']
  },
  {
    id: '6',
    src: 'https://picsum.photos/300/200?random=6',
    title: '质量检测图6',
    width: 300,
    height: 200,
    thumbnailUrl: 'https://picsum.photos/300/200?random=6',
    keywords: ['质量', '检测', '监控']
  }
]; */
// 图片搜索相关状态
/* const imageSearch = ref({
  keyword: '',
  page: 1,
  pageSize: 4,
  loading: false,
  images: mockImageDatabase, // 直接使用mock数据
  hasMore: false,
  total: mockImageDatabase.length
}); */
// 简化的搜索函数
/* const searchImages = async (isLoadMore = false) => {
  try {
    imageSearch.value.loading = true;

    // 根据关键词过滤图片
    const filteredImages = imageSearch.value.keyword
      ? mockImageDatabase.filter((img) => img.title.toLowerCase().includes(imageSearch.value.keyword.toLowerCase()))
      : mockImageDatabase;

    imageSearch.value.images = filteredImages;
    imageSearch.value.total = filteredImages.length;
    imageSearch.value.hasMore = false; // 暂时禁用加载更多功能
  } finally {
    imageSearch.value.loading = false;
  }
}; */
// 防抖处理的搜索函数
/* const debounceSearch = useDebounceFn(() => {
  searchImages(false);
}, 300); */

// 组件挂载时加载图片
/* onMounted(() => {
  searchImages(false);
}); */
// 已加载图片集合
// const loadedImages = ref(new Set<string>());
// 加载更多图片
/* const loadMoreImages = () => {
  if (!imageSearch.value.loading && imageSearch.value.hasMore) {
    searchImages(true);
  }
}; */
// 处理图片加载完成
/* const handleImageLoad = (src: string) => {
  loadedImages.value.add(src);
}; */
// 添加一个计算属性来判断是否可以插入图片
/* const canInsertImage = computed(() => {
  const isEnabled = isDirectoryContentTab.value && selectedNode.value && isCursorInEditor.value;
  console.log('Button state:', {
    tab: activeContentTab.value,
    selectedNode: selectedNode.value,
    cursorInEditor: isCursorInEditor.value,
    isEnabled
  });
  return isEnabled;
}); */
// 获取章节内容的通用方法
/* const getChapterContent = async (node: any) => {
  try {
    // 构建pathBySerial数组
    const pathArray = node.chapterNumber.split('.').map(Number);

    const params = {
      bid: biddoc.bid || 'e628fd93-82de-565c-bfab-aec220108c2e',
      version: 'ver_0000',
      pathBySerial: pathArray
    };

    const { data } = await getChildernBidserial(params);
    if (data) {
      return {
        chapter: data.chapter,
        content: data.children || '暂无内容',
        words: data.words,
        pages: data.pages
      };
    }
  } catch (error) {
    ElMessage.error('获取章节内容失败');
    console.error('获取章节内容失败:', error);
  }
  return null;
};
 */
// 获取写作状态文本
const getWriteStatus = (data: any) => {
  const isLeafCompleted = data.wordCount <= userBalance.value / costPerWord;

  return {
    text: isLeafCompleted ? "已完成" : "未完成",
    type: isLeafCompleted ? "success" : "warning",
    showBalance: !isLeafCompleted,
  };
};
// 计算每字费用（模拟数据，实际应从配置获取）
const costPerWord = 0.01; // 假设每字0.01元
// 添加下载函数
const downloadBidDocument = async () => {
  try {
    // 检查是否已经在生成中
    if (generatingBids.value.has(biddoc.bid)) {
      ElMessage.info('标书正在后台生成中，生成完成后可在"我的标书"中下载');
      return;
    }
    // 显示确认对话框
    await ElMessageBox.confirm(
      '标书生成需要较长时间，生成完后，请在"我的标书"里面下载',
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }
    );
    // 调用生成接口
    const response = await getfull({
      outline_id: selectedOutlineId.value || "string",
      user_id: "string",
      bid: biddoc.bid,
      version: "ver_0000",
      limit: -1,
    });
    if (response.code === 200) {
      // 将当前标书ID添加到生成中集合
      generatingBids.value.add(biddoc.bid);
      // 更新按钮状态
      ElMessage.success('标书已开始生成，请在"我的标书"中查看进度');
    } else {
      ElMessage.error(response.msg || "生成失败，请重试");
    }
  } catch (error) {
    ElMessage.error("生成失败，请重试");
  }
};
// 监听标签页切换
watch(activeContentTab, (newVal) => {
  if (newVal === "content" && selectedNode.value) {
    // 当切换到正文模式时，确保设置当前节点
    nextTick(() => {
      setCurrentNode(selectedNode.value?.id);
    });
  }
});
// 添加新的状态变量
const isDirectoryLoading = ref(false);
const directoryLoadingProgress = ref(0);
const directoryLoadingText = ref("正在生成目录...");

// 添加表格样式处理函数
const processTableStyles = (content: string) => {
  if (!content) return content;

  // 创建临时div来解析HTML
  const tempDiv = document.createElement("div");
  tempDiv.innerHTML = content;

  // 查找所有表格并添加样式
  const tables = tempDiv.getElementsByTagName("table");
  for (let table of tables) {
    // 添加基础表格样式类
    table.className = "el-table el-table--border";

    // 处理表头
    const thead = table.getElementsByTagName("thead")[0];
    if (thead) {
      thead.className = "el-table__header";
      const ths = thead.getElementsByTagName("th");
      for (let th of ths) {
        th.className = "el-table__cell";
      }
    }

    // 处理表格主体
    const tbody = table.getElementsByTagName("tbody")[0];
    if (tbody) {
      tbody.className = "el-table__body";
      const trs = tbody.getElementsByTagName("tr");
      for (let tr of trs) {
        tr.className = "el-table__row";
        const tds = tr.getElementsByTagName("td");
        for (let td of tds) {
          td.className = "el-table__cell";
        }
      }
    }
  }
  return tempDiv.innerHTML;
};
// 添加新的状态变量
const isPolling = ref(true);
/* watch(
  () => route.query.id,
  (newId) => {
    if (newId) {
      // 使用新的 id 获取数据
      console.log(newId);
    }
  }
);
 */
// 添加生成状态管理
const generatingBids = ref(new Set());
// 监听路由参数变化
watch(
  () => route.query,
  async (query) => {
    if (eventSourceInstance.value) {
      eventSourceInstance.value.close();
    }
    if (query.id && query.is_my_bid) {
      // 切换到正文模式
      activeStep.value = 3;
      activeContentTab.value = "content";
      modeStore.setContentMode(activeContentTab.value === "content");
      let catalogData = null;
      biddoc.bid = query.id as string;
      treeLoading.value = true;
      try {
        // 处理目录数据
        const result = await getCatalogByBid({
          doc_id: biddoc.bid,
          outline_id: selectedOutlineId.value,
        });
        if (result?.data) {
          catalogData = result.data?.outline?.catalog;
          totalPages.value = result.data?.total_page;
          totalWords.value = result.data?.total_words;
        }
                /* await getfull({
          uname:'1',
          bid: biddoc.bid,
          version: 'ver_0000',
          bulk_num: 1,
          limit: 3s
        }); */
        // 检查数据有效性
        if (!catalogData || !catalogData?.length>0) {
          throw new Error("目录数据无效");
        }

        // 处理章节数据
        formattedChapters.value = formatChapter(catalogData);
        // 等待DOM更新
        await nextTick();
        // 查找并选择第一个叶子节点
        const findFirstLeafNode = (nodes: any[]): any => {
          if (!Array.isArray(nodes)) return null;

          for (const node of nodes) {
            if (node.isLeaf) {
              return node;
            }
            if (node.children && node.children.length > 0) {
              const leaf = findFirstLeafNode(node.children);
              if (leaf) return leaf;
            }
          }
          return null;
        };
        const firstLeafNode = findFirstLeafNode(formattedChapters.value);
        if (firstLeafNode) {
          // 设置当前选中节点
          selectedNode.value = {
            id: firstLeafNode.id,
            label: firstLeafNode.title,
            content: firstLeafNode.content,
            isLeaf: firstLeafNode.isLeaf,
            pageCount: firstLeafNode.pageCount,
            wordCount: firstLeafNode.wordCount,
            chapterNumber: firstLeafNode.chapterNumber,
          };
          // 设置树形控件的当前选中节点
          contentTreeRef.value?.setCurrentKey(firstLeafNode.id);
          // 设置当前轮询节点标识符
          currentPollingNodeId.value = firstLeafNode.id;
          // 加载节点内容
          const pathArray = firstLeafNode.chapterNumber
            .split(".")
            .map(Number)
            .join(".");
          isContentChanged.value = false;
          /*  isPolling.value = true;
          isFirstPoll.value = true; */
          startStream(biddoc.bid, pathArray);
        }
      } catch (error) {
        console.error("获取目录数据失败:", error);
        ElMessage.error("获取目录数据失败");
      } finally {
        treeLoading.value = false;
      }
    }
  },
  { immediate: true }
);
const emit = defineEmits(["update:mode"]);
const handleTabChange = async () => {
  // 如果是预览模式，跳过默认的标签页切换逻辑
  console.log("handleTabChange 开始执行");
  console.log("isPreviewMode.value:", isPreviewMode.value);
  console.log("activeContentTab.value:", activeContentTab.value);
  if (isPreviewMode.value) {
    console.log("预览模式，跳过轮询");
    return;
  }
  nextTick(async () => {
    console.log("nextTick 回调执行");
    console.log("activeContentTab.value:", activeContentTab.value);
    if (activeContentTab.value === "content") {
      console.log("切换到正文模式，开始查找叶子节点");
      console.log("formattedChapters.value:", formattedChapters.value);
      // 直接内联查找第一个叶子节点的逻辑
      const findFirstLeafNode = (nodes: any[]): any => {
        if (!Array.isArray(nodes)) {
          console.log("nodes 不是数组:", nodes);
          return null;
        }

        for (const node of nodes) {
          if (node.isLeaf) {
            console.log("找到叶子节点:", node);
            return node;
          }
          if (node.children && node.children.length > 0) {
            const leaf = findFirstLeafNode(node.children);
            if (leaf) return leaf;
          }
        }
        console.log("没有找到叶子节点");
        return null;
      };
      const firstLeafNode = findFirstLeafNode(formattedChapters.value);
      if (firstLeafNode) {
        // 设置当前选中节点
        selectedNode.value = {
          id: firstLeafNode.id,
          label: firstLeafNode.title,
          content: firstLeafNode.content,
          isLeaf: firstLeafNode.isLeaf,
          pageCount: firstLeafNode.pageCount,
          wordCount: firstLeafNode.wordCount,
          chapterNumber: firstLeafNode.chapterNumber,
        };
        // 设置树形控件的当前选中节点
        contentTreeRef.value?.setCurrentKey(firstLeafNode.id);
        // 设置当前轮询节点标识符
        currentPollingNodeId.value = firstLeafNode.id;
        // 加载节点内容
        const pathArray = firstLeafNode.chapterNumber
          .split(".")
          .map(Number)
          .join(".");
        /*   isPolling.value = true;
        isFirstPoll.value = true; */
        startStream(biddoc.bid, pathArray);
      }
    }
  });
};
// 修改插入图片函数
/* const insertImageToContent = (image:any) => {
  
  if (!selectedNode.value || !contentEditor.value) {
    ElMessage.warning('请先选择要插入图片的章节');
    return;
  }

  try {
    // 获取当前光标位置
    const selection:any = window.getSelection();
    console.log('Current selection:', selection);
    
    if (!selection || selection.rangeCount === 0) {
      // 如果没有选中区域，在编辑器末尾插入
      const range = document.createRange();
      range.selectNodeContents(contentEditor.value);
      range.collapse(false); // 折叠到末尾
      selection.removeAllRanges();
      selection.addRange(range);
    }
    
    const range = selection.getRangeAt(0);
    console.log('Current range:', range);
    
    // 创建图片元素
    const img = document.createElement('img');
    img.src = image.src;
    img.alt = image.title;
    img.style.maxWidth = '100%';
    img.style.height = 'auto';
    // img.style.margin = '10px auto'; // 修改为 auto 实现水平居中
    img.style.display = 'block'; // 添加 display: block
    
    // 在光标位置插入图片
    range.deleteContents();
    range.insertNode(img);
    
    // 移动光标到图片后面
    range.setStartAfter(img);
    range.collapse(true);
    selection.removeAllRanges();
    selection.addRange(range);
    
    // 更新内容
    const newContent = contentEditor.value.innerHTML;
    if (selectedNode.value) {
      selectedNode.value.content = newContent;
    }
    
    // 触发内容更新
    onContentInput();
    
    ElMessage.success('图片插入成功');
  } catch (error) {
    console.error('插入图片失败:', error);
    ElMessage.error('插入图片失败，请重试');
  }
} */
// 监听 activeContentTab 的变化
watch(activeContentTab, (newValue) => {
  modeStore.setContentMode(newValue === "content");
});

// 在挂载时调用
onMounted(() => {
  resetDirectoryState();
  directoryState.value = DirectoryState.INITIAL;
});

// 添加进度条状态变量
const directoryLoadingStatus = ref("");

// 动态进度条工具函数
const animateProgress = (targetProgress: number, duration: number = 2000, onComplete?: () => void) => {
  const startProgress = directoryLoadingProgress.value;
  const progressDiff = targetProgress - startProgress;
  const startTime = Date.now();
  
  const updateProgress = () => {
    const elapsed = Date.now() - startTime;
    const progress = Math.min(elapsed / duration, 1);
    
    // 使用缓动函数让进度条更自然
    const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3);
    const easedProgress = easeOutCubic(progress);
    
    directoryLoadingProgress.value = Math.floor(startProgress + progressDiff * easedProgress);
    
    if (progress < 1) {
      requestAnimationFrame(updateProgress);
    } else {
      directoryLoadingProgress.value = targetProgress;
      if (onComplete) {
        onComplete();
      }
    }
  };
  
  requestAnimationFrame(updateProgress);
};

// 添加一个响应式变量来跟踪光标位置
const isCursorInEditor = ref(false);

// 添加检查光标位置的函数
/* const checkCursorPosition = () => {
  const contentBody = document.querySelector('.content-body');
  if (!contentBody) {
    isCursorInEditor.value = false;
    return;
  }

  // 检查鼠标是否在编辑区域内
  const rect = contentBody.getBoundingClientRect();
  const isMouseInEditor = (
    event.clientX >= rect.left &&
    event.clientX <= rect.right &&
    event.clientY >= rect.top &&
    event.clientY <= rect.bottom
  );

  // 检查是否有选中的内容
  const selection = window.getSelection();
  const hasSelection = selection && selection.rangeCount > 0;
  
  if (hasSelection) {
    const range = selection.getRangeAt(0);
    isCursorInEditor.value = contentBody.contains(range.commonAncestorContainer);
  } else {
    isCursorInEditor.value = isMouseInEditor;
  }
};
 */
// 设置内容编辑区域的事件监听
const setupContentEditor = () => {
  const contentBody = document.querySelector(".content-body");
  if (contentBody) {
    // 监听鼠标进入事件
    contentBody.addEventListener("mouseenter", () => {
      isCursorInEditor.value = true;
    });

    // 监听鼠标离开事件
    contentBody.addEventListener("mouseleave", () => {
      isCursorInEditor.value = false;
    });

    // 监听获得焦点事件
    contentBody.addEventListener("focus", () => {
      isCursorInEditor.value = true;
    });

    // 监听失焦事件
    contentBody.addEventListener("blur", () => {
      isCursorInEditor.value = false;
    });
  }
};

// const isDirectoryContentTab = computed(() => activeContentTab.value === 'content');
// 在组件挂载时设置事件监听
onMounted(() => {
  setupContentEditor();
  const contentBody = document.querySelector(".content-body");
  if (contentBody) {
    contentBody.addEventListener("focus", handleEditorFocus, true);
    contentBody.addEventListener("blur", handleEditorBlur, true);
    contentBody.addEventListener("click", () => {
      isCursorInEditor.value = true;
      console.log("Editor clicked, cursor state:", isCursorInEditor.value);
    });
  }
});

// 在组件卸载时移除事件监听
onBeforeUnmount(() => {
  const contentBody = document.querySelector(".content-body");
  if (contentBody) {
    contentBody.removeEventListener("mouseenter", () => {
      isCursorInEditor.value = true;
    });
    contentBody.removeEventListener("mouseleave", () => {
      isCursorInEditor.value = false;
    });
    contentBody.removeEventListener("focus", () => {
      isCursorInEditor.value = true;
    });
    contentBody.removeEventListener("blur", () => {
      isCursorInEditor.value = false;
    });
  }
});

/* // 添加鼠标事件处理函数
const handleEditorMouseEnter = () => {
  console.log('Mouse Enter');
  isCursorInEditor.value = true;
};

const handleEditorMouseLeave = () => {
  console.log('Mouse Leave');
  isCursorInEditor.value = false;
}; */

// 确保在组件挂载时初始化状态
onMounted(() => {
  isCursorInEditor.value = false;
  selectedNode.value = null;
});

// 添加按钮提示信息的计算属性
/* const getButtonTooltip = computed(() => {
  if (!isDirectoryContentTab.value) return '请在正文模式下使用';
  if (!selectedNode.value) return '请先选择章节';
  if (!isCursorInEditor.value) return '请先点击编辑区域设置光标位置';
  return '点击插入图片';
});
 */
// 添加内容输入处理方法
const onContentInput = () => {
  if (contentEditor.value && selectedNode.value) {
    // 更新节点内容
    selectedNode.value.content = contentEditor.value.innerHTML;
    // 设置内容已改变
    isContentChanged.value = true;
  }
};

// 确保在组件挂载时初始化编辑器
onMounted(() => {
  nextTick(() => {
    if (contentEditor.value) {
      contentEditor.value.innerHTML = selectedNode.value?.content || "";
    }
  });
});
const handleEditorFocus = () => {
  isCursorInEditor.value = true;
  console.log("Editor focused, cursor state:", isCursorInEditor.value);
};

const handleEditorBlur = (event: any) => {
  console.log("Editor blur event triggered");
  // 检查是否点击了插入图片按钮
  const target = event.relatedTarget;
  console.log("Blur related target:", target);

  if (target && target.classList.contains("insert-image-button")) {
    console.log("Clicked insert image button, keeping focus");
    return; // 如果点击的是插入图片按钮，不失去焦点
  }

  // 使用 nextTick 确保在 DOM 更新后再设置状态
  nextTick(() => {
    isCursorInEditor.value = false;
    console.log("Editor blurred, cursor state:", isCursorInEditor.value);
  });
};

// 在组件挂载时设置事件监听
onMounted(() => {
  const contentBody = document.querySelector(".content-body");
  if (contentBody) {
    contentBody.addEventListener("focus", handleEditorFocus, true);
    contentBody.addEventListener("blur", handleEditorBlur, true);
    contentBody.addEventListener("click", () => {
      isCursorInEditor.value = true;
    });
  }
});

// 在组件卸载时移除事件监听
onBeforeUnmount(() => {
  const contentBody = document.querySelector(".content-body");
  if (contentBody) {
    contentBody.removeEventListener("focus", handleEditorFocus, true);
    contentBody.removeEventListener("blur", handleEditorBlur, true);
    contentBody.removeEventListener("click", () => {
      isCursorInEditor.value = true;
    });
  }
});

// 编辑器点击事件处理
const handleEditorClick = () => {
  console.log("Editor clicked");
  isCursorInEditor.value = true;
};
// 处理插入图片按钮点击
/* const handleInsertImage = (image:any) => {
  console.log('Insert image button clicked');
  console.log('Current cursor state:', isCursorInEditor.value);
  
  // 确保编辑器有焦点
  if (contentEditor.value) {
    contentEditor.value.focus();
    // 使用 nextTick 确保焦点设置完成
    nextTick(() => {
      insertImageToContent(image);
    });
  }
}; */

// 在组件挂载时初始化
onMounted(() => {
  console.log("Component mounted");
  // 初始化编辑器状态
  isCursorInEditor.value = false;
  selectedNode.value = null;

  // 确保编辑器引用存在
  nextTick(() => {
    if (contentEditor.value) {
      console.log("Content editor initialized");
      contentEditor.value.innerHTML = selectedNode.value?.content || "";
    }
    console.log("refresh cateTimer onMounted");
    if(cateTimer.value != null){
       clearInterval(cateTimer.value);
       cateTimer.value = null;
    }
    setCateTimer();
  });
});
const cateTimer = ref<any>(null);
const setCateTimer = async  () => { 
  const changeState: any = (chapters: any[], parentNumber = "") => {
    if (!Array.isArray(chapters)) {
      console.error("Invalid chapters data:", chapters);
    }
    chapters.map((chapter, index) => {
      const currentNumber = parentNumber ? `${parentNumber}.${index + 1}`: `${chapter.serial}`;
      if(chapter.isGenerate){
         let targetNode = findNodeByNumber(formattedChapters.value, currentNumber);
         if(!targetNode.isGenerate){
            console.log("generate:", currentNumber, targetNode);
            targetNode.isGenerate = true;
         }
      }
      if(chapter.children){
        changeState(chapter.children, currentNumber)
      }
    });
  };
  const runOne = async () => {
    const timeRes = await getCatalogByBid({
      doc_id: biddoc.bid,
      outline_id: selectedOutlineId.value,
    });
    if(timeRes?.data?.outline?.catalog){
      console.log("cateTimer runOne update state");
      changeState(timeRes?.data?.outline?.catalog);
    }
    return timeRes?.data?.is_finally
  };
  console.log("setCateTimer",'|', biddoc?.bid,'|', cateTimer.value);
  if(biddoc?.bid && cateTimer.value == null){
    let isFinally = await runOne();
    if (!isFinally){
        cateTimer.value = setInterval(async () => {
          isFinally = await runOne();
          if(isFinally){
            clearInterval(cateTimer.value);
          }
      }, 5000);
    }
  }
};

// 添加目录树宽度相关的响应式变量
const treeWidth = ref(300); // 默认宽度
const isResizing = ref(false);
const startX = ref(0);
const startWidth = ref(0);

// 添加拖动相关的方法
const startResize = (e) => {
  isResizing.value = true;
  startX.value = e.clientX;
  startWidth.value = treeWidth.value;

  document.addEventListener("mousemove", handleResize);
  document.addEventListener("mouseup", stopResize);
};

const handleResize = (e: any) => {
  if (!isResizing.value) return;

  // 使用 requestAnimationFrame 提高性能和流畅度
  requestAnimationFrame(() => {
    const deltaX = e.clientX - startX.value;
    const newWidth = startWidth.value + deltaX;

    // 限制最小和最大宽度
    if (newWidth >= 200 && newWidth <= 800) {
      // 增大最大宽度限制
      treeWidth.value = newWidth;
    }
  });
};

const stopResize = () => {
  isResizing.value = false;
  document.removeEventListener("mousemove", handleResize);
  document.removeEventListener("mouseup", stopResize);

  // 添加过渡效果，使停止拖动后有平滑效果
  const treeElement = document.querySelector(".directory-tree-wrapper");
  if (treeElement) {
    treeElement.classList.add("resize-transition");
    setTimeout(() => {
      treeElement.classList.remove("resize-transition");
    }, 300);
  }
};

// 组件卸载时清理事件监听
onBeforeUnmount(() => {
  if (isResizing.value) {
    stopResize();
  }
});
// 文件上传前验证
const beforeUpload = (file: File) => {
  // 检查文件类型
  const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                 file.name.toLowerCase().endsWith('.docx');
  if (!isDocx) {
    ElMessage.error('只支持 .docx 格式文件！');
    return false;
  }
  
  // 检查文件大小（5MB = 5 * 1024 * 1024 bytes）
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过 5MB！');
    return false;
  }
  
  return true;
};
</script>

<style scoped lang="scss">
.add-tender-container {
  width: 100%;
  height: 100%;
  padding: 0;
  display: flex;
  flex-direction: column;
}
.el-tabs.el-tabs--top.el-tabs--border-card {
  height: 90%;
}
.steps-container {
  padding: 15px 20px;
  position: relative;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-steps) {
  --el-color-primary: #1890ff;
}
.content-loading {
  padding: 20px;
  text-align: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  margin-bottom: 20px;

  .loading-text {
    margin-top: 10px;
    color: #606266;
    font-size: 14px;
  }
}
.knowledge-base-option {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.knowledge-base-option:hover {
  border-color: #1890ff;
  background-color: #f0f9ff;
}

.knowledge-base-option :deep(.el-checkbox) {
  width: 100%;
  height: 100%;
  margin-right: 0;
}

/* 选中状态的样式 */
.knowledge-base-option :deep(.el-checkbox.is-checked) {
  background-color: #e6f7ff;
  border-radius: 8px;
  padding: 16px;
  margin: -16px;
}

.knowledge-base-option
  :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #1890ff;
  font-weight: 500;
}

.knowledge-base-option
  :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #1890ff;
  border-color: #1890ff;
}

.knowledge-base-option :deep(.el-checkbox__label) {
  font-size: 15px;
  color: #606266;
}

.knowledge-base-option :deep(.el-checkbox__inner) {
  border-radius: 4px;
  border-color: #dcdfe6;
}

.knowledge-base-option :deep(.el-checkbox__inner:hover) {
  border-color: #1890ff;
}
// 优化内容显示动画
.content-body {
  transition: all 0.3s ease;

  p {
    margin: 0;
    padding: 8px 0;
    animation: fadeIn 0.5s ease;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
:deep(.el-step__title) {
  font-size: 15px;
  font-weight: 500;
  color: #909399;
  transition: all 0.3s;
}
:deep(.el-card__body) {
  overflow: auto;
}
:deep(.el-step__head.is-process) {
  color: var(--el-color-primary);
  border-color: var(--el-color-primary);
}
:deep(.el-step__icon.is-text) {
  border: 2px solid;
  font-weight: bold;
}

:deep(.el-step__head.is-process .el-step__icon.is-text) {
  background-color: var(--el-color-primary);
  color: white;
}

:deep(.el-step__head.is-wait .el-step__icon.is-text) {
  border-color: #c0c4cc;
  color: #c0c4cc;
}

:deep(.el-step__head.is-finish .el-step__icon.is-text) {
  background-color: #e6f7ff;
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.step-content {
  flex: 1;
  padding: 10px;
  background-color: white;
  overflow-y: auto;
}

.setting-item {
  margin-bottom: 24px;
}

.setting-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #303133;
}

.page-count-slider {
  padding: 0 10px;
  margin-bottom: 16px;
}

.word-count-info {
  margin-top: 16px;
}

:deep(.el-alert__title) {
  font-size: 16px;
  font-weight: 600;
}

:deep(.el-alert__description) {
  font-size: 14px;
}

.sub-setting {
  margin-bottom: 20px;
}

.sub-setting-title {
  font-size: 16px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 12px;
}

.option-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.option-card {
  display: flex;
  align-items: center;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  flex: 1;
  min-width: 180px;
  max-width: calc(33.33% - 11px);
}

.option-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.option-card.active {
  border-color: #1890ff;
  background-color: #e6f7ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.option-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  margin-right: 10px;
  color: white;
  font-size: 16px;
  flex-shrink: 0;
}

.option-icon.technical {
  background: linear-gradient(135deg, #1890ff, #096dd9);
}

.option-icon.business {
  background: linear-gradient(135deg, #13c2c2, #08979c);
}

.option-icon.custom {
  background: linear-gradient(135deg, #722ed1, #531dab);
}

.option-icon.none {
  background: linear-gradient(135deg, #bfbfbf, #8c8c8c);
}

.option-icon.moderate {
  background: linear-gradient(135deg, #52c41a, #389e0d);
}

.option-icon.extensive {
  background: linear-gradient(135deg, #fa8c16, #d46b08);
}

.option-content {
  flex-grow: 1;
}

.option-title {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.option-description {
  font-size: 12px;
  color: #4b5563;
  line-height: 1.4;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 30px;
  min-height: 40px;
  position: relative;
}

.step-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 24px;
  color: #303133;
}

.upload-mode-selector {
  margin-bottom: 20px;
}

.paste-area {
  width: 100%;
}

.option-item {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.option-description {
  margin-top: 8px;
  color: #606266;
  font-size: 14px;
}

.knowledge-base-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
  margin-top: 12px;
}

.knowledge-base-card {
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.knowledge-base-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.knowledge-base-card.active {
  border-color: #1890ff;
  background-color: #e6f7ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.kb-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.kb-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  margin-right: 10px;
  color: white;
  font-size: 16px;
}

.kb-icon.industry {
  background: linear-gradient(135deg, #1890ff, #096dd9);
}

.kb-icon.company {
  background: linear-gradient(135deg, #13c2c2, #08979c);
}

.kb-icon.legal {
  background: linear-gradient(135deg, #fa8c16, #d46b08);
}

.kb-icon.technical {
  background: linear-gradient(135deg, #722ed1, #531dab);
}

.kb-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.kb-description {
  color: #4b5563;
  font-size: 14px;
  line-height: 1.5;
}

.option-icon.government {
  background: linear-gradient(135deg, #1890ff, #096dd9);
}

.option-icon.enterprise {
  background: linear-gradient(135deg, #13c2c2, #08979c);
}

.option-icon.international {
  background: linear-gradient(135deg, #fa8c16, #d46b08);
}

.option-icon.ppp {
  background: linear-gradient(135deg, #722ed1, #531dab);
}

.paste-section {
  margin-bottom: 20px;
}

.paste-section-title {
  font-size: 16px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 12px;
}

.paste-container {
  display: flex;
  gap: 20px;
}

.paste-section {
  flex: 1;
  margin-bottom: 0;
}

.reference-upload-section {
  margin-bottom: 20px;
}

.knowledge-base-selection {
  margin-top: 20px;
}

.selection-title {
  font-size: 16px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 12px;
}

.knowledge-base-cards.compact {
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
}
.custom-style-dialog {
  border-radius: 12px;
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.15);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 目录编写区域样式 */
.directory-container {
  overflow-y: auto;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}
.directory-container-writing {
  overflow-y: auto;
  height: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 40px;
}

.directory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background-color: #f8f9fa;
  border-radius: 8px;
  // margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.directory-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.directory-title h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.user-balance {
  background-color: #fff;
  padding: 8px 16px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.balance-info {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
}

.balance-info.insufficient {
  color: #f56c6c;
}

.directory-tree {
  flex: 1;
  background-color: #fff;
  /*   border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05); */
}

.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.chapter-number {
  font-weight: 600;
  color: #1890ff;
  min-width: 20px;
}

.chapter-title {
  color: #303133;
  font-size: 14px;
  flex: 1;
}

.node-info {
  display: flex;
  align-items: center;
  margin-left: auto;
  opacity: 0.8;
  transition: opacity 0.3s;
}

.custom-tree-node:hover .node-info {
  opacity: 1;
}

.status-tags {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-tag {
  min-width: 64px;
  text-align: center;
  border-radius: 12px;
}

.count-tags {
  display: flex;
  gap: 8px;
}

.count-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  border-radius: 12px;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.count-tag .el-icon {
  font-size: 12px;
}

.preview-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  border-radius: 12px;
  transition: all 0.3s;
}

.preview-button:hover {
  background-color: #ecf5ff;
  transform: translateY(-1px);
}

.preview-button .el-icon {
  font-size: 14px;
}

/* 树节点hover效果 */
:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

/* 选中节点样式 */
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
}

.node-actions {
  opacity: 0;
  transition: opacity 0.3s;
}

.custom-tree-node:hover .node-actions {
  opacity: 1;
}

.el-tree-node__content {
  height: auto !important;
  padding: 4px 0;
}

.generating-dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.generating-text {
  margin-top: 20px;
  font-size: 16px;
  color: #606266;
}

.directory-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 200px);
  overflow: hidden;
}

.directory-sidebar {
  width: 35%;
  min-width: 300px;
  display: flex;
  flex-direction: column;
}

.directory-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-tabs__content) {
  flex: 1;
  overflow-y: auto;
}

.sidebar-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.score-points-list {
  overflow-y: auto;
}

.score-point-item {
  margin-bottom: 15px;
  padding: 12px;
  border-radius: 6px;
  background-color: #f8f9fa;
  border-left: 3px solid #1890ff;
}

.score-point-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.score-value {
  font-weight: 600;
  color: #f56c6c;
}

.score-point-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.project-overview-content {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
  line-height: 1.6;
  max-height: 100%;
  overflow-y: auto;
}

.directory-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.directory-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.directory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.directory-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.directory-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.directory-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.directory-stats {
  display: flex;
  gap: 10px;
}

.chapters-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

:deep(.el-collapse-item__header) {
  font-size: 16px;
  font-weight: 500;
}

.chapter-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chapter-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chapter-number {
  font-weight: 600;
  color: #1890ff;
}

.chapter-name {
  cursor: pointer;
}

.chapter-name:hover {
  color: #1890ff;
  text-decoration: underline;
}

.chapter-edit-input {
  width: 300px;
}

.chapter-info {
  display: flex;
  gap: 8px;
}

.chapter-content {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.chapter-thought h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.thought-textarea {
  width: 100%;
}

.chapter-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 8px;
}



/* 添加章节按钮 - 白色文字 - 使用更高优先级的选择器 */
.chapter-actions .el-button[type="primary"],
.chapter-actions .el-button[type="primary"].is-plain,
.chapter-actions .el-button[type="primary"] span,
.chapter-actions .el-button[type="primary"].is-plain span {
  color: white !important;
  -webkit-text-fill-color: white !important;
}

.chapter-actions .el-button[type="primary"] .el-icon,
.chapter-actions .el-button[type="primary"].is-plain .el-icon {
  color: white !important;
  -webkit-text-fill-color: white !important;
}

/* 删除按钮 - 白色文字 */
.chapter-actions .el-button[type="danger"],
.chapter-actions .el-button[type="danger"].is-plain,
.chapter-actions .el-button[type="danger"] span,
.chapter-actions .el-button[type="danger"].is-plain span {
  color: white !important;
  -webkit-text-fill-color: white !important;
}

.chapter-actions .el-button[type="danger"] .el-icon,
.chapter-actions .el-button[type="danger"].is-plain .el-icon {
  color: white !important;
  -webkit-text-fill-color: white !important;
}

/* 上移下移按钮(plain) - 保持默认样式 */
.chapter-actions .el-button.is-plain:not([type="danger"]):not([type="primary"]),
.chapter-actions .el-button.is-plain:not([type="danger"]):not([type="primary"]) span {
  color: #606266 !important;
  -webkit-text-fill-color: #606266 !important;
}

.add-chapter-button {
  margin: 20px 0;
  text-align: center;
}

.directory-submit {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.directory-placeholder {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 50px;
}

/* 修改目录方案选择区域的滚动样式 */
.directory-options {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 10px;
  /* 移除这个固定高度和溢出设置，让外层控制滚动 */
  /* max-height: calc(100vh - 270px); */
  /* overflow-y: auto; */
}

/* 确保外层卡片可以滚动 */
.directory-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  flex: 1;
  overflow-y: auto; /* 只保留外层卡片的滚动 */
  padding: 15px;
}

/* 修改目录预览区域，去掉滚动设置 */
.directory-preview {
  /* 移除固定高度和溢出设置 */
  /* max-height: 300px; */
  /* overflow-y: auto; */
}

/* 修改方案卡片样式，保持完整显示 */
.directory-option-card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 弹性曲线 */
  margin-bottom: 25px;
  background-color: white;
  position: relative;
}

.directory-option-card:hover:not(.selected) {
  transform: translateY(-3px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08);
  border-color: #d9d9d9;
}

.directory-option-card:active:not(.selected) {
  transform: scale(0.98);
}

/* 添加选中方案时的闪光效果 */
@keyframes selectGlow {
  0% {
    box-shadow: 0 0 0 rgba(24, 144, 255, 0);
  }
  50% {
    box-shadow: 0 0 15px rgba(24, 144, 255, 0.4);
  }
  100% {
    box-shadow: 0 8px 16px rgba(24, 144, 255, 0.15);
  }
}

.directory-option-card.selected {
  animation: selectGlow 0.6s forwards;
}

/* 修改 content-writing 样式以适应固定底部栏 */
.content-writing {
  height: 100%;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
}

/* 调整 tabs 容器样式以留出底部空间 */
.content-writing .el-tabs {
  flex: 1;
  overflow: hidden;
  /*  margin-bottom: 60px; /* 为底部按钮留出空间 */
}

/* 固定底部栏样式 */
.fixed-bottom-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 55px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  z-index: 100;
}

/* 下载按钮样式 */
.fixed-bottom-bar .el-button {
  min-width: 160px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 24px;
  transition: all 0.3s;
}

.fixed-bottom-bar .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.content-editor {
  padding: 20px;
}

.custom-tree-node {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;
}

.node-actions {
  opacity: 0;
  transition: opacity 0.3s;
}

.custom-tree-node:hover .node-actions {
  opacity: 1;
}

.section-title {
  margin: 15px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  text-align: center;
}

/* 添加新的样式 */
.selected-plan-edit {
  border: 1px solid #1890ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.selected-plan-tag {
  margin-right: 8px;
}

.chapters-list.selected-plan {
  margin-top: 10px;
}

.chapter-content.selected-plan-content {
  background: linear-gradient(to right, #f0f9ff, #f9f9f9);
  border-left: 3px solid #1890ff;
  padding: 20px;
  position: relative;
  transition: all 0.3s;
}

.chapter-content.selected-plan-content:hover {
  box-shadow: 0 0 10px rgba(24, 144, 255, 0.1);
}

.selected-plan-content .thought-textarea {
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  background-color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s;
}

.selected-plan-content .thought-textarea:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 添加章节AI操作按钮样式 */
.chapter-ai-actions {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
  margin: 15px 0;
  padding-bottom: 15px;
  border-bottom: 1px dashed #e0e0e0;
}

.chapter-ai-actions .el-button {
  transition: all 0.3s;
}

.chapter-ai-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 单个编写正文按钮的样式 */
.single-button {
  margin: 0 auto;
  font-size: 16px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s;
  display: block;
}

.single-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

/* 选中的方案卡片样式优化 */
.directory-option-card.selected {
  border: 2px solid #1890ff;
  background: linear-gradient(to bottom right, #f0f9ff, #e6f7ff);
  box-shadow: 0 8px 16px rgba(24, 144, 255, 0.15);
  transform: translateY(-5px) scale(1.02);
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
}

/* 添加悬停效果，提示可以取消选中 */
.directory-option-card.selected:hover {
  border-color: #40a9ff;
  background: linear-gradient(to bottom right, #e6f7ff, #d9f0ff);
  cursor: pointer;
}

/* 添加提示文本 */
/* .directory-option-card.selected:hover::before {
  content: "点击取消选择";
  position: absolute;
  top: -20px;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 10;
} */

/* 添加选中标记 */
.directory-option-card.selected::before {
  content: "";
  position: absolute;
  top: -10px;
  right: -10px;
  width: 35px;
  height: 35px;
  background: #1890ff;
  border-radius: 50%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  z-index: 2;
}

/* 添加选中标记内的对勾 */
.directory-option-card.selected::after {
  content: "✓";
  position: absolute;
  top: -6px;
  right: -1px;
  color: white;
  font-size: 18px;
  font-weight: bold;
  z-index: 3;
}

/* 选中方案的标题样式 */
.directory-option-card.selected .option-header h3 {
  color: #1890ff;
  font-weight: 600;
}

/* 选中方案的标签样式 */
.directory-option-card.selected .directory-stats .el-tag {
  border-color: #1890ff;
  background-color: rgba(24, 144, 255, 0.1);
  color: #1890ff;
  font-weight: 500;
}

/* 方案卡片内部元素布局优化 */
.option-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.option-header h3 {
  margin: 0;
  font-size: 18px;
  color: #262626;
  transition: all 0.3s;
}

.directory-preview {
  padding: 10px;
  background-color: #fafafa;
  border-radius: 6px;
  margin-bottom: 15px;
}

.directory-preview .chapter-title {
  font-weight: 600;
  color: #262626;
  margin: 12px 0 8px 0;
}

.directory-preview .sub-chapter {
  padding-left: 20px;
  color: #595959;
  font-size: 14px;
  margin: 6px 0;
  position: relative;
}

.directory-preview .sub-chapter::before {
  content: "•";
  position: absolute;
  left: 8px;
  color: #1890ff;
}

.directory-stats {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
}

.directory-stats .el-tag {
  transition: all 0.3s;
}

/* 添加选择提示样式 */
.selection-tip {
  display: flex;
  align-items: center;
  gap: 10px;
}

.tip-text {
  font-size: 14px;
  color: #606266;
}
.page-layout {
  display: flex;
  gap: 20px;
  height: 100%;
  overflow: hidden;
}

.page-layout .directory-tree {
  border-right: 1px solid #e4e7ed;
  padding-right: 20px;
  overflow-y: auto;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 20px;
}

.content-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.content-header h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #303133;
}

.content-info {
  display: flex;
  gap: 10px;
}
.content-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.balance-warning {
  display: flex;
  align-items: center;
  gap: 4px;
  border-radius: 12px;
  background-color: #fef0f0;
  color: #f56c6c;
  cursor: pointer;
  transition: all 0.3s;
}

.balance-warning:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(245, 108, 108, 0.2);
}

.balance-warning .el-icon {
  font-size: 12px;
}

/* 正文模式部分的修改 */
.content-writing .el-tabs .el-tab-pane {
  height: 100%;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
}

/* 调整 tabs 容器样式以留出底部空间 */
.content-writing .el-tabs {
  flex: 1;
  overflow: hidden;
  /*  margin-bottom: 60px; /* 为底部按钮留出空间 */
}

.directory-tree-content {
  width: 230px;
  border-right: 1px solid #e4e7ed;
  overflow: auto; // 修改为 auto，同时支持横向和纵向滚动
  background: #fff;
}

/* 右侧内容区域 */
.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 20px;
}

/* 目录树节点样式优化 */
.directory-tree-content :deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
}

/* 目录树节点高亮 */
.directory-tree-content
  :deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 内容区域样式优化 */
.content-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.content-header h2 {
  margin: 0 0 12px 0;
  font-size: 22px;
  color: #303133;
  font-weight: 600;
}

.content-info {
  display: flex;
  gap: 12px;
}

.content-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

/* 树节点内容样式优化 */
.directory-tree-content .custom-tree-node {
  width: 100%;
  font-size: 13px;
}

.directory-tree-content .node-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.directory-tree-content .chapter-number {
  color: #1890ff;
  font-weight: 500;
}

.directory-tree-content .chapter-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.content-area {
  display: flex;
  height: 100%;
}

.image-search-panel {
  width: 250px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-header {
  padding: 12px;
  border-bottom: 1px solid #dcdfe6;
}

.image-container {
  flex: 1;
  overflow-y: auto;
  padding: 12px 12px 22px 12px;
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background: #f5f7fa;
  }
}

.image-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.image-item {
  min-height: 200px; // 确保有最小高度
  background: #fff;
  padding: 10px;
}

.image-wrapper {
  width: 100%;
  height: 120px;
  border: 1px solid #ddd;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.image-info {
  padding: 8px;

  .image-title {
    display: block;
    margin-bottom: 8px;
    font-size: 12px;
  }
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  color: #909399;
}

.loading-more .el-icon {
  margin-right: 8px;
}

.content-writing-layout {
  display: flex;
  height: 100%;
  overflow: hidden;
}

.content-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  position: relative;
  overflow: hidden; // 防止内容溢出
}

.content-body-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
  border-radius: 4px;

  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    background: #fff;
    position: relative;
    z-index: 1;
  }

  .node-info {
    flex: 1;
    margin-right: 16px;
    padding: 12px 16px;
    background: #e6f7ff;
    border-radius: 6px;
    border: 1px solid #91d5ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
    position: relative;
    overflow: hidden;

    &::before {
      content: "";
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 4px;
      background: #1890ff;
    }

    .node-title {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .chapter-number {
      color: #fff;
      font-size: 16px;
      font-weight: 600;
      background: #1890ff;
      padding: 4px 12px;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
    }

    .chapter-title {
      font-size: 18px;
      font-weight: 600;
      color: #1890ff;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }
  }

  .save-button-container {
    flex-shrink: 0;
  }

  .content-body {
    flex: 1;
    padding: 15px;
    margin-bottom: 50px;
    border: 1px solid #e4e7ed;
    overflow-y: auto;
    min-height: 0;

    // 自定义滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c0c4cc;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background: #f5f7fa;
    }

    // 图片样式
    :deep(img) {
      max-width: 100%;
      height: auto;
      margin: 10px auto;
      display: block;
    }
  }
}

.image-placeholder,
.image-error {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;

  .el-icon {
    font-size: 24px;
  }
}

.image-info {
  .el-button {
    &[disabled] {
      cursor: not-allowed;
      opacity: 0.6;
    }
  }
}

.preview-content {
  margin: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.content-info {
  margin: 10px 0;
  color: #666;
}

.content-info span {
  margin-right: 20px;
}

.writing-mode {
  display: flex;
  gap: 20px;
}

.chapter-tree {
  width: 300px;
  border-right: 1px solid #eee;
}

.content-area {
  flex: 1;
  padding: 20px;
}

.content-body {
  line-height: 1.6;
}

.content-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  color: #909399;
}

.content-loading .el-progress {
  margin-right: 10px;
}

.loading-text {
  font-size: 14px;
  color: #606266;
}

// 添加表格样式
:deep(.el-table) {
  width: 100%;
  margin: 16px 0;
  border-collapse: collapse;
  border: 1px solid #ebeef5;

  .el-table__header {
    background-color: #f5f7fa;

    .el-table__cell {
      padding: 12px 0;
      font-weight: 500;
      color: #606266;
      border-bottom: 1px solid #ebeef5;
      text-align: left;
    }
  }

  .el-table__body {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }

      .el-table__cell {
        padding: 12px 0;
        color: #606266;
        border-bottom: 1px solid #ebeef5;
      }
    }
  }

  // 添加斑马纹样式
  .el-table__row:nth-child(even) {
    background-color: #fafafa;
  }

  // 添加边框样式
  .el-table__cell {
    border-right: 1px solid #ebeef5;

    &:last-child {
      border-right: none;
    }
  }
}

// 确保表格在内容区域正确显示
.content-body {
  :deep(table) {
    display: table;
    width: 100%;
    margin: 16px 0;
  }

  :deep(th),
  :deep(td) {
    padding: 12px 8px;
    text-align: left;
    vertical-align: middle;
  }
}

.content-writing-layout {
  display: flex;
  height: 100%;

  .directory-tree-wrapper {
    min-width: 200px;
    border-right: 1px solid #e4e7ed;
    overflow: auto;

    :deep(.directory-tree) {
      width: 100%;

      .el-tree-node {
        width: 100%;

        .el-tree-node__content {
          width: 100%;
          height: auto;
          min-height: 32px;
          padding: 4px 0;
        }
      }
    }
  }
  .tree-node {
    display: flex;
    align-items: center;
    width: 100%;
    min-width: 280px;
    padding-right: 8px;

    .chapter-number {
      flex-shrink: 0;
      // width: 30px;
      // margin-right: 8px;
    }

    .chapter-title {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

// 自定义滚动条样式
:deep(.directory-tree-wrapper) {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background: #f5f7fa;
  }
}

.content-body {
  :deep(img) {
    max-width: 100%;
    height: auto;
    margin: 10px auto;
    display: block;
  }
}

.image-list {
  .image-item {
    .image-wrapper {
      img {
        max-width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}

.content-writing-layout {
  display: flex;
  height: 100%;
  gap: 20px;

  .content-main {
    flex: 1;
    min-width: 0; // 防止内容溢出
    display: flex;
    flex-direction: column;
    height: 100%;

    .content-body-wrapper {
      display: flex;
      flex-direction: column;
      height: 100%;
      background: #fff;
      border-radius: 4px;

      .save-button-container {
        padding: 12px;
        display: flex;
        justify-content: flex-end;
        background: #fff;
      }

      .content-body {
        flex: 1;
        padding: 15px;
        margin-bottom: 50px;
        border: 1px solid #e4e7ed;
        overflow-y: auto;
        border: 1px solid #e4e7ed;
        min-height: 0; // 重要：允许内容区域收缩

        // 自定义滚动条样式
        &::-webkit-scrollbar {
          width: 6px;
        }

        &::-webkit-scrollbar-thumb {
          background: #c0c4cc;
          border-radius: 3px;
        }

        &::-webkit-scrollbar-track {
          background: #f5f7fa;
        }

        // 图片样式
        :deep(img) {
          max-width: 100%;
          height: auto;
          margin: 10px auto;
          display: block;
        }
      }
    }
  }
}

.directory-tree-wrapper {
  position: relative;
  min-width: 200px;
  // max-width: 400px;
  border-right: 1px solid #e4e7ed;
  overflow: auto;
  background: #fff;
  transition: width 0.1s ease;
}

.resize-handle {
  position: absolute;
  top: 0;
  right: -10px; /* 向右偏移更多 */
  width: 20px; /* 进一步增加宽度 */
  height: 100%;
  cursor: col-resize;
  background-color: transparent;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 添加明显的视觉指示 */
.resize-handle::before {
  content: "";
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 4px; /* 增加宽度 */
  height: 100%;
  background-color: #e0e0e0; /* 默认颜色 */
  border-radius: 2px;
  transition: background-color 0.2s;
}

/* 悬停状态 */
.resize-handle:hover::before {
  background-color: #1890ff; /* 蓝色 */
  box-shadow: 0 0 8px rgba(24, 144, 255, 0.5); /* 添加发光效果 */
}

/* 活动状态 */
.resize-handle:active::before {
  background-color: #096dd9; /* 深蓝色 */
  box-shadow: 0 0 12px rgba(24, 144, 255, 0.7); /* 增强发光效果 */
}

/* 添加拖动指示图标 */
.resize-handle::after {
  content: "⋮⋮"; /* 使用垂直点作为拖动指示 */
  position: absolute;
  color: #909399;
  font-size: 18px;
  font-weight: bold;
  letter-spacing: -2px;
  transition: color 0.2s;
}

.resize-handle:hover::after {
  color: #1890ff;
}

/* 移除旧的图标样式 */
.resize-icon {
  display: none;
}

/* 添加拖动时的全局样式 */
.is-resizing {
  cursor: col-resize !important;
  user-select: none !important;
}

/* 优化拖拽手柄样式，使其更加明显 */
.resize-handle {
  position: absolute;
  top: 0;
  right: -8px; /* 向右偏移，增大可点击区域 */
  width: 16px; /* 增加宽度 */
  height: 100%;
  cursor: col-resize;
  background-color: transparent;
  transition: all 0.2s;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
}

.resize-handle:hover {
  background-color: rgba(245, 247, 250, 0.8);
}

.resize-handle:active {
  background-color: rgba(230, 247, 255, 0.8);
}

.resize-icon {
  font-size: 16px;
  color: #909399;
  transform: rotate(90deg);
  transition: color 0.2s;
  opacity: 0.6; /* 降低默认状态下的不透明度 */
}

.resize-handle:hover .resize-icon {
  color: #1890ff;
  opacity: 1; /* 悬停时完全不透明 */
}

/* 添加拖拽过渡效果 */
.directory-tree-wrapper {
  position: relative;
  min-width: 200px;
  max-width: 800px; /* 增大最大宽度 */
  border-right: 1px solid #e4e7ed;
  background: #fff;
  transition: none; /* 拖动时不使用过渡效果，保证实时响应 */
}

/* 拖拽结束时的过渡效果 */
.directory-tree-wrapper.resize-transition {
  transition: width 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 使用弹性曲线 */
}

/* 添加拖拽指示线 */
.resize-handle::after {
  content: "";
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 2px;
  height: 100%;
  background-color: #dcdfe6;
  opacity: 0;
  transition: opacity 0.2s;
}

.resize-handle:hover::after {
  opacity: 0.8;
}

.resize-handle:active::after {
  opacity: 1;
  background-color: #409eff;
}

/* 确保目录树填充整个容器 */
.directory-tree-wrapper .directory-tree {
  height: 100%;
  margin: 0;
}

/* 调整内容区域的布局 */
.content-writing-layout {
  display: flex;
  height: 100%;
  overflow: hidden;
}

.content-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  position: relative;
  overflow: hidden;
}

.directory-tree-wrapper {
  position: relative;
  min-width: 200px;
  max-width: 800px;
  border-right: 1px solid #e4e7ed;
  background: #fff;
  transition: width 0.1s ease;
  /* 移除 overflow: auto，改为在内部元素控制滚动 */
  display: flex;
  flex-direction: column;
}

/* 添加一个内部容器来处理滚动 */
.directory-tree-container {
  flex: 1;
  margin-bottom: 50px;
  overflow-y: auto;
  overflow-x: hidden;
  /* 确保内容不会被拖动条遮挡 */
  // padding-right: 16px;
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background: #f5f7fa;
  }
}

/* 确保目录树填充整个容器 */
.directory-tree {
  height: 100%;
  margin: 0;
  /* 移除可能的多余内边距 */
  padding: 0;
}

/* 调整树节点的样式 */
:deep(.el-tree-node__content) {
  padding: 8px 0;
  /* 确保内容不会溢出 */
  min-width: 0;
}

:deep(.el-tree-node__content .el-tree-node__label) {
  /* 确保文本可以正确换行 */
  white-space: normal;
  word-break: break-word;
}

/* 确保自定义树节点内容正确显示 */
.custom-tree-node {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 8px;
  /* 防止内容溢出 */
  min-width: 0;
}

.node-content {
  flex: 1;
  /* 防止内容溢出 */
  min-width: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.chapter-number {
  /* 固定宽度，防止数字变化导致布局抖动 */
  min-width: 20px;
  text-align: right;
}

.chapter-title {
  flex: 1;
  /* 允许文本换行 */
  white-space: normal;
  word-break: break-word;
  /* 防止内容溢出 */
  min-width: 0;
}

.thought-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.thought-header h4 {
  margin: 0;
}

.edit-icon {
  font-size: 16px;
  color: #909399;
  cursor: pointer;
  transition: color 0.2s;
}

.edit-icon:hover {
  color: #409eff;
}

.thought-textarea {
  width: 100%;
}

.content-body {
  position: relative;
  min-height: 200px;
}

:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.9) !important;
}

:deep(.el-loading-spinner) {
  .el-loading-text {
    color: #409eff;
    font-size: 16px;
    font-weight: bold;
    margin-top: 10px;
  }

  .circular {
    width: 42px;
    height: 42px;
  }
}
.thinking-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
}

.thinking-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
}

.thinking-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.thinking-content {
  text-align: center;
}

.thinking-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 20px;
  animation: rotate 1.5s linear infinite;
}
.thinking-text {
  color: #606266;
  font-size: 16px;
  font-weight: 500;
}

.dialog-footer {
  text-align: center;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.icon-loading {
  animation: icon-rotate 1s linear infinite;
  display: inline-block;
}
@keyframes icon-rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 状态图标容器 */
.status-icon-wrap {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  // margin-right: 8px;
}

/* 加载中状态图标 */
.status-icon.status-loading {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.status-icon.status-loading svg {
  color: #409eff;
  animation: icon-rotate 1.5s linear infinite;
  background: linear-gradient(135deg, #409eff 0%, #36cfc9 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 成功状态图标 */
.status-icon.status-success {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.status-icon.status-success svg {
  color: #67c23a;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 旋转动画 */
@keyframes icon-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.node-info {
  padding: 12px;
}

.node-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chapter-number {
  font-weight: bold;
  color: #1890ff;
}

.chapter-title {
  font-size: 16px;
  color: #303133;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #fff;
}

.node-info {
  flex: 1;
}

.node-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chapter-title {
  font-weight: 500;
  color: #303133;
}

.save-button-container {
  flex-shrink: 0;
}

/* 新增：优化节点信息与编辑区样式 */
.content-writing-layout .content-main .content-body-wrapper {
  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #ebeef5;
    background: #fff;
  }
  .node-info {
    flex: 1;
    margin-right: 16px;
    padding: 8px 12px;
    background: #f8f9fa;
    border-radius: 4px;
    .node-title {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    .chapter-number {
      color: #000000;
      font-size: 20px;
      font-weight: 1000;
      background: #f0f2f5;
      padding: 2px 8px;
      border-radius: 3px;
    }
    .chapter-title {
      font-size: 20px;
      font-weight: 1000;
      color: #000000;
    }
  }
  .save-button-container {
    flex-shrink: 0;
  }
  .content-body {
    flex: 1;
    padding: 20px;
    margin-bottom: 50px;
    overflow-y: auto;
    min-height: 0;
    outline: none !important; // 彻底移除编辑区聚焦时的黑色边框
    border: 1px solid #e4e7ed;
    &:focus {
      outline: none !important;
    }
    &::-webkit-scrollbar {
      width: 6px;
    }
    &::-webkit-scrollbar-thumb {
      background: #dcdfe6;
      border-radius: 3px;
    }
    &::-webkit-scrollbar-track {
      background: #f5f7fa;
    }
    :deep(img) {
      max-width: 100%;
      height: auto;
      margin: 10px auto;
      display: block;
    }
  }
}
/* 目录树节点编号高亮，仅作用于左侧目录树 */
.directory-tree-wrapper .chapter-number {
  color: #1890ff;
  font-size: 13px;
  font-weight: 600;
  border-radius: 4px;
  margin-right: 6px;
  letter-spacing: 0.5px;
  display: inline-block;
  box-shadow: 0 1px 2px rgba(24, 144, 255, 0.06);
}

/* 确保弹窗垂直居中 */
.upload-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  /* 添加垂直居中样式 */
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
/* 标题区域美化 */
.upload-dialog :deep(.el-dialog__header) {
  padding: 20px 24px 14px 24px;
  border-bottom: 1.5px solid #409eff;
  background: #fff;
}

/* 标题字体美化 */
.upload-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 700;
  color: #222;
  letter-spacing: 0.5px;
}

/* 内容区域适度padding */
.upload-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

/* 简化标题样式 */
.custom-dialog-header {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  padding: 16px 24px;
  margin: 0;
  text-align: center;
  position: relative;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
  color: white;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: white;
}

.header-title p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
  font-weight: 400;
}

.upload-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 22px;
  font-weight: 700;
  letter-spacing: 0.8px;
  /* 美化标题文字 */
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  position: relative;
  z-index: 1;
  /* 添加微妙的动画效果 */
  animation: titleGlow 2s ease-in-out infinite alternate;
}

.upload-dialog :deep(.el-dialog__body) {
  padding: 32px;
}

.upload-dialog :deep(.el-dialog__footer) {
  padding: 20px 32px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  text-align: center;
}

.upload-dialog-content {
  text-align: center;
}

.upload-progress {
  padding: 20px 0;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.progress-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.progress-percentage {
  font-size: 20px;
  font-weight: 700;
  color: #409eff;
  background: linear-gradient(135deg, #409eff, #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.progress-bar {
  margin-bottom: 20px;
}

.upload-dialog :deep(.el-progress-bar__outer) {
  background-color: #f5f7fa;
  border-radius: 10px;
}

.upload-dialog :deep(.el-progress-bar__inner) {
  border-radius: 10px;
  transition: all 0.3s ease;
}

.upload-status {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-top: 16px;
}

.uploading-icon {
  color: #409eff;
  font-size: 18px;
  animation: rotate 1s linear infinite;
}

.success-icon {
  color: #67c23a;
  font-size: 18px;
}

.status-text {
  font-size: 15px;
  color: #666;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.dialog-footer .el-button {
  min-width: 100px;
  height: 40px;
  border-radius: 20px;
  font-weight: 600;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 上传区域样式 */
.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  transition: all 0.3s ease;
  padding: 20px;
}

.upload-area:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.upload-area.has-file {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-dialog :deep(.el-dialog) {
    width: 90% !important;
    /* 保持垂直居中 */
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: 0;
  }

  .upload-dialog :deep(.el-dialog__body) {
    padding: 20px;
  }

  .progress-header {
    flex-direction: column;
    gap: 10px;
  }

  .upload-dialog :deep(.el-dialog__title) {
    font-size: 20px;
  }
}
.node-status-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  width: 100%;
}

// .node-status-container .status-tag {
//   margin-right: auto; /* 状态标签靠左 */
// }

.node-status-container .count-tags {
  display: flex;
  gap: 4px;
}

.node-status-container .count-tag {
  display: flex;
  align-items: center;
  gap: 2px;
}

.node-status-container .balance-warning {
  display: flex;
  align-items: center;
  gap: 2px;
}
.node-status-container .preview-button {
  margin-left: 8px;
}
</style>
